Arrays: Left Rotation

Sort by

recency

|

4979 Discussions

|

  • + 0 comments

    Python efficient using mod:

    def rotLeft(a, d): 
        realRots = d % len(a) 
        return a[realRots:] + a[:realRots]
    
  • + 0 comments

    Python:

    def rotLeft(a, d):
        # Write your code here
        for i in range(d):
            item = a.pop(0)
            a.append(item)
        return a
    
  • + 0 comments

    Python:

        for i in range(d):
            item = a.pop(0)
            a.append(item)
        return a
    
  • + 0 comments

    This is a Golang efficient solution:

    func rotLeftEfficient(a []int32, d int32) []int32 {
    	size := int32(len(a))
    	// Ensure d is within range
    	d = d % size
    
    	// Rearranging elements directly
    	return append(a[d:], a[:d]...)
    }
    
  • + 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;
    }