Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. The rotation should happen in-place.
Constraints:
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 10 <= 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
Approach: Reversal Algorithm
This problem can be solved efficiently in O(n) time and O(1) extra space using the reversal algorithm.
- Handle
kreduction: First, reducektok % n, wherenis the length of the array. Ifkis a multiple ofn, no rotation is needed. - Reverse the entire array: Reverse all elements from index
0ton-1. - Reverse the first
kelements: Reverse the elements from index0tok-1. - Reverse the remaining
n - kelements: Reverse the elements from indexkton-1.
This sequence of reversals effectively rotates the array to the right.
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 # Reduce k to avoid unnecessary full rotations
if k == 0: # No rotation needed
return
# Helper function to reverse a sub-array
def reverse_sub_array(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_sub_array(nums, 0, n - 1)
# Step 2: Reverse the first k elements
reverse_sub_array(nums, 0, k - 1)
# Step 3: Reverse the remaining n - k elements
reverse_sub_array(nums, k, n - 1)
