Shift left, Rotate left in Array

Concept: Shift Left and Rotate Left in an Array

Shift Left

Shifting an array to the left means moving its elements one position to the left, and the leftmost element is removed. For example, shifting [1, 2, 3, 4] left results in [2, 3, 4, 0] if you fill the rightmost position with zero.

Rotate Left

Rotating an array to the left means moving its elements one position to the left, and the leftmost element wraps around to the end of the array. For example, rotating [1, 2, 3, 4] left results in [2, 3, 4, 1].


Example Code

Java

Shift Left
1
2
3
4
5
6
7
8
public class Main {
    public static void shiftLeft(int[] arr) {
        for(int i = 0; i < arr.length - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[arr.length - 1] = 0;
    }
}
Rotate Left
1
2
3
4
5
6
7
8
9
public class Main {
    public static void rotateLeft(int[] arr) {
        int firstElement = arr[0];
        for(int i = 0; i < arr.length - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[arr.length - 1] = firstElement;
    }
}

C++

Shift Left
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <vector>
using namespace std;

void shiftLeft(vector<int>& arr) {
    for(int i = 0; i < arr.size() - 1; ++i) {
        arr[i] = arr[i + 1];
    }
    arr[arr.size() - 1] = 0;
}
Rotate Left
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostream>
#include <vector>
using namespace std;

void rotateLeft(vector<int>& arr) {
    int firstElement = arr[0];
    for(int i = 0; i < arr.size() - 1; ++i) {
        arr[i] = arr[i + 1];
    }
    arr[arr.size() - 1] = firstElement;
}

Python

Shift Left
1
2
3
4
def shift_left(arr):
    for i in range(len(arr) - 1):
        arr[i] = arr[i + 1]
    arr[-1] = 0
Rotate Left
1
2
3
4
5
def rotate_left(arr):
    first_element = arr[0]
    for i in range(len(arr) - 1):
        arr[i] = arr[i + 1]
    arr[-1] = first_element

Key Takeaways

  • Shift Left: Elements are moved one position left, and the last position is filled with a default value (usually zero).
  • Rotate Left: Elements are moved one position left, and the first element wraps around to fill the last position.
  • Both operations can be done in a single pass through the array, making them time-efficient.