Arrays: Left Rotation

Sort by

recency

|

4984 Discussions

|

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

    C++ solution

    vector<int> rotLeft(vector<int> a, int d) {
        while(d)
        {
            int temp = a[0];
            a.push_back(temp);
            a.erase(a.begin());
            d--;
        }
        
        return a;
    }
    
  • + 0 comments
        int n = a.Count;
    
        for (int i = 0; i < d; i++)
        {
            int firstElement = a[0];
            a.RemoveAt(0);
            a.Insert(n - 1, firstElement);
        }
    
        return a;