Left Rotation

Sort by

recency

|

152 Discussions

|

  • + 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])
    }
    
  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn left_rotation(d: i32, arr: &[i32]) -> Vec<i32> {
        //Time complexity: O(n)
        //Space complexity (ignoring input): O(n)
        let mut new_array = Vec::new();
        for index in 0..arr.len() {
            new_array.push(arr[(index + d as usize) % arr.len()]);
        }
    
        new_array
    }