Easy Slicing Arrays & Strings
In plain English: Shift every element k positions to the left, wrapping elements from the front to the back.
The 3-reverse trick works because reversing segments then the whole array is equivalent to a cyclic shift — no extra space needed.
Prompt
Given array a and integer k, return the left-rotated array.
Try to write it from scratch before scrolling down.
Solution
def left_rotate(a, k):
k = k % len(a) # handle wrap-around
return a[k:] + a[:k]
# Test: left_rotate([1,2,3,4,5], 2) == [3,4,5,1,2]
# In-place variant (3 reverses):
def left_rotate_inplace(a, k):
k = k % len(a)
def rev(lo, hi):
while lo < hi:
a[lo], a[hi] = a[hi], a[lo]
lo += 1; hi -= 1
rev(0, k - 1)
rev(k, len(a) - 1)
rev(0, len(a) - 1)