Left Rotation

Sort by

recency

|

153 Discussions

|

  • + 0 comments
    def rotateLeft(d, arr):
        for i in range(d):
            arr.append(arr.pop(0))
        return arr
    
  • + 0 comments

    I think this solution only few line in java

        public static List<Integer> rotateLeft(int d, List<Integer> arr) {
            for(int i=0; i < d; i++){
                arr.add(arr.remove(0));
            }
            return arr;
        }
    
  • + 0 comments

    Python Solution with minimum no of rotations remainder = minimum no. of rotations or swaps required on the arr

    def rotateLeft(d, arr):
        n=len(arr)
        rem=d%n
        if d==0 or rem==0:
            return arr
        else:
            for i in range(rem):
                arr.append(float('-inf'))
                arr[0],arr[-1]=arr[-1],arr[0]
                arr.pop(0)
            return arr
    
  • + 0 comments

    Java Easy solution

    public static List<Integer> rotateLeft(int d, List<Integer> arr) {
    
        if(d==arr.size()){
            return arr;
        }
        int i=0;
        for(;i<d;d--){
            int temp = arr.get(i);
            arr.remove(i);
            arr.add(temp);
        }
        return arr;
    }
    
  • + 0 comments

    Swift solution:

    func rotateLeft(d: Int, arr: [Int]) -> [Int] {
        let n = arr.count
        
        // 'mod' operation avoids unnecessary rotations
        let rotations = d % n
        
        return Array(arr[rotations...] + arr[..<rotations])
    }