Arrays: Left Rotation

Sort by

recency

|

4986 Discussions

|

  • + 0 comments
    def rotLeft(a, d):
        # Write your code here
        n = len(a)
        nums = []
        js = []
        for i, num in enumerate(a):
            j = i-d
            if j < 0:
                j = n+j
            else:
                j = j
            js.append(j)
            nums.append(num)
        new_a = sorted(zip(js, nums))
        arr = []
        for item in new_a:
            arr.append(item[1])
        return arr
    
  • + 0 comments

    Java 8

    Time complexity - O(n)

    I calculate each item's new index after d rotations and add it to a new list.

    public static List<Integer> rotLeft(List<Integer> a, int d) {
            // Write your code here
            // d<=n
            List<Integer> rusultList = new ArrayList<>();
            
            for(int i=0; i<a.size(); i++) {
                rusultList.add(a.get((i+d) % a.size()));
            }
            return rusultList;
            
        }
    
  • + 0 comments
    function rotLeft(a: number[], d: number): number[] {
       return [ ...a.slice(d), ...a.slice(0, d)]
    }
    
  • + 0 comments

    Without memory allocation Golang O(n) solution:

    func rotLeft(a []int32, d int32) []int32 {
    	size := int32(len(a))
    	d = d % size
    	if d == 0 {
    		return a
    	}
    
    	m, n, r := 0, d, d
    	for i := int32(1); i <= d && n < size; i++ {
    		x := a[m]
    		a[m] = a[n]
    		a[n] = x
    
    		m++
    		n++
    		r--
    	}
    
    	if n == size {
    		rotLeft(a[m:], r)
    	} else {
    		rotLeft(a[d:], d)
    	}
    
    	return a
    }
    
  • + 1 comment

    Python solution:

    def rotLeft(a, d):
            return a[d%len(a):] + a[:d%len(a)]