The most efficient way to rotate an array in-place is using the "Reverse" technique. If we reverse the whole array, then reverse the first k elements, and finally reverse the remaining elements, we get the rotated array.
- Normalize
kby takingk % len(nums)because rotatinglen(nums)times is equivalent to zero rotation. - Define a helper function
reverse(start, end)to swap elements until pointers meet. - Reverse the entire array from index
0ton-1. - Reverse the first part from index
0tok-1. - Reverse the second part from index
kton-1.
- Time Complexity: O(N), as we visit each element a constant number of times.
- Space Complexity: O(1), as the rotation is done in-place.
def rotate(nums, k):
n = len(nums)
k %= n
def reverse(l, r):
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
# Step 1: Reverse entire array
reverse(0, n - 1)
# Step 2: Reverse first k elements
reverse(0, k - 1)
# Step 3: Reverse the rest
reverse(k, n - 1)
return nums