Left Rotation

Sort by

recency

|

150 Discussions

|

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

    Python 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

    def left_rotation(d, arr):
        # Time complexity: O(n)
        # Space complexity (ignoring input): O(n)
        new_array = [0] * len(arr)
        for index in range(0, len(arr)):
            new_array[(index - d) % len(arr)] = arr[index]
    
        return new_array
    
    
    def left_rotation_in_place(d, arr):
        # Time complexity: O(n)
        # Space complexity (ignoring input): O(1)
        n = len(arr)
        start_range = 0
        end_range = d
        for index in range(0, (end_range - start_range) // 2):
            arr[index + start_range], arr[end_range - index - 1] = (
                arr[end_range - index - 1],
                arr[index + start_range],
            )
    
        start_range = d
        end_range = n
        for index in range(0, (end_range - start_range) // 2):
            arr[index + start_range], arr[end_range - index - 1] = (
                arr[end_range - index - 1],
                arr[index + start_range],
            )
    
        start_range = 0
        end_range = n
        for index in range(0, (end_range - start_range) // 2):
            arr[index + start_range], arr[end_range - index - 1] = (
                arr[end_range - index - 1],
                arr[index + start_range],
            )
    
        return arr
    
  • + 0 comments
    #python solution
    def rotateLeft(d, arr):
        return arr[d:]+arr[:d]