Arrays: Left Rotation

Sort by

recency

|

4973 Discussions

|

  • + 0 comments
        public static List<Integer> rotLeft(List<Integer> a, int d) {     
            List<Integer> rotations = new ArrayList<>();
            // Elements from index d to the end
            rotations.addAll(a.subList(d, a.size())); 
            // Elements from the start to index d
            rotations.addAll(a.subList(0, d)); 
            
            return rotations;
        }
    
  • + 0 comments

    C# this is with basic knowledge

    public static List rotLeft(List a, int d) {

            int length=a.Count()-1;
            int[] newArr = new int[length+1];
    
            for(int i = length;i>-1;i--){
    
                if(i-d<0)
                {                   
                    int j=i-d;                   
                    newArr[length+1+j]=a[i];                      
                }
                else
                {
                    newArr[i-d]=a[i];
                }
            }
            return   newArr.ToList() ;
    }
    

    }

  • + 0 comments

    Solution for c#.

    public static List<int> rotLeft(List<int> a, int d)
    {
    	int n = a.Count;
    	int rotateBy = d % n;
    
    	List<int> rotatedPart = a.GetRange(0, rotateBy);
    	a.RemoveRange(0, rotateBy);
    	a.AddRange(rotatedPart);
    
    	return a;
    
    }
    
  • + 0 comments

    Here is the optimal approach by using recursion and reversing the array.

    //swap array elements void swap(int &a, int &b) { int temp = a; a = b; b = temp; }

    void reverse(vector &arr, int i, int j) { if (i >= j) return; // Base condition to stop recursion swap(arr[i], arr[j]); reverse(arr, i + 1, j - 1); }

    vector rotLeft(vector a, int d) { int n = a.size(); d = d % n; // Handle cases where d >= n reverse(a, 0, d - 1); // Reverse the first part reverse(a, d, n - 1); // Reverse the second part reverse(a, 0, n - 1); // Reverse the whole array return a; }

  • + 3 comments

    Java

    public static List rotLeft(List a, int d) { while(d>0) { Integer removed = a.remove(0); a.add(removed); d--; } return a; } }