Arrays: Left Rotation

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