Rotate Array Problem
Description
LeetCode Problem 189.
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
- 0 <= k <= 10^5
Solution
Approach: Three Reversals
Shifting the array right by one step, k times, takes O(n · k) time. Copying into a second array is O(n) but needs O(n) extra space. Three reversals do it in place in O(n).
Rotating right by k moves the last k elements to the front, keeping the order inside both parts. Reversing the whole array puts the last k elements at the front, but each part is now backwards. Reversing each part again fixes that:
nums = [1,2,3,4,5,6,7], k = 3
reverse all: [7,6,5,4,3,2,1]
reverse first k = 3: [5,6,7,4,3,2,1]
reverse the rest: [5,6,7,1,2,3,4]
The detail that is easy to miss: k can be larger than the length n. Rotating by n steps gives back the same array, so first replace k with k % n. Without it, the second and third reversals use indices past the end of the array.
The reversal is the usual two-pointer swap: swap nums[left] and nums[right], then move both pointers inward until they meet.
Complexity: O(n) time and O(1) extra space, where n is the length of nums.
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n # rotating by n steps changes nothing
self._reverse(nums, 0, n - 1) # [1,2,3,4,5,6,7] -> [7,6,5,4,3,2,1]
self._reverse(nums, 0, k - 1) # first k: [5,6,7,4,3,2,1]
self._reverse(nums, k, n - 1) # the rest: [5,6,7,1,2,3,4]
def _reverse(self, nums: List[int], left: int, right: int) -> None:
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
Now write it from memory
Close the write-up and solve it yourself against the tests.