Arrays: Left Rotation

Sort by

recency

|

4975 Discussions

|

  • + 0 comments

    public static List rotLeft(List a, int d) { // Write your code here int n = a.size(); d = d % n; // Handle cases where d > n

    // Use sublists to rearrange in O(n) time
    List<Integer> rotated = new ArrayList<>(a.subList(d, n));
    rotated.addAll(a.subList(0, d));
    
    return rotated;
    }
    
  • + 1 comment

    Python code -

  • + 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;
    
    }