I have a question where I need to rotate an array left k times.
i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]
So, my code is:
def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t
return a
where n = length of the array.
I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.
What is wrong with my solution?
i==0
andk==1
(the shift of the first element by one position to the right).a[i] = a[(i+n-1+k)%n]
becomesa[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]
. Is this right? – Forerunnerprint
ing the value of(i+n-1+k)%n
so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result? – Topdress