Given an integer array nums, rotate the array to the right by k steps. The rotation should be in-place if possible.
- Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^90 <= k <= 10^5
- Example:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 step 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]
Solution
This problem can be solved in several ways, with varying space complexities. A common trick for in-place rotation involves reversals.
- Understanding the effective rotations:
- First, calculate
k = k % nwherenis the length ofnums. This handles cases wherekis larger thann.
- First, calculate
- Approach using Reversals (Optimal Space):
- Step 1: Reverse the entire array. This brings the elements that should be at the end to the beginning (in reverse order) and vice-versa.
- Step 2: Reverse the first
kelements. This corrects the order of the elements that moved from the end to the front. - Step 3: Reverse the remaining
n - kelements (from indexkton-1). This corrects the order of the elements that moved from the front to the end.
- Example Walkthrough:
nums = [1,2,3,4,5,6,7],k = 3(n=7,k=3%7=3)- Original:
[1,2,3,4,5,6,7] - Reverse all:
[7,6,5,4,3,2,1] - Reverse first
k=3elements:[5,6,7,4,3,2,1] - Reverse remaining
n-k=4elements:[5,6,7,1,2,3,4](Final Result)
- Original:
- Time Complexity: O(N) because each element is reversed at most three times.
- Space Complexity: O(1) as the operations are performed in-place.
class Solution:
def rotate(self, nums: list[int], k: int) -> None:
n = len(nums)
k %= n # Handle cases where k > n
# Helper function to reverse a sub-array
def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# Step 1: Reverse the entire array
reverse(nums, 0, n - 1)
# Step 2: Reverse the first k elements
reverse(nums, 0, k - 1)
# Step 3: Reverse the remaining n-k elements
reverse(nums, k, n - 1)