Left Rotation

Sort by

recency

|

144 Discussions

|

  • + 0 comments

    C++ Solution:

    vector rotateLeft(int d, vector arr) {

    auto calcOldIndex = [](int newIndex, int shift, int size) 
    {
        int tmp = newIndex + shift;
        if(tmp >= size)
            tmp = tmp - size;
        return tmp;
    };
    
    vector<int> res;
    
    for(int i = 0; i < (int)arr.size(); i++){
        res.push_back(arr[calcOldIndex(i, d, arr.size())]);
    }
    return res;
    

    }

  • + 0 comments

    python 3

    def rotateLeft(d, arr):
    return map(lambda x: arr[(x[0]+d) % len(arr)], enumerate(arr))
    
  • + 0 comments

    My rust solution:

    fn rotateLeft(d: i32, arr: &mut [i32]) {
        arr.rotate_left(d as usize);
    }
    
  • + 0 comments
    def rotateLeft(d, arr):
        # Write your code here
        for i in range(d):
            arr.append(arr[i])
        return arr[d:]
    
  • + 0 comments

    Ugly Python3 in-place solution: O(N) time, O(1) space

    def rotateLeft(d, arr, lo = 0):
        n = len(arr) - lo
        d = d % n
        if d == 0:
            return arr
        r = n - d
            
        for i in range(r):
            arr[lo + i], arr[lo + d + i] = arr[lo + d + i], arr[lo + i]
        return rotateLeft(d - r, arr, lo + r)