Given an integer array nums, 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 <= 105-231 <= nums[i] <= 231 - 10 <= k <= 105Follow up:
O(1) extra space?When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a row of items and you want to shift them all to the right by a certain number of steps, so that the items falling off the right side wrap around to the front. The brute force approach achieves this by repeatedly moving just the very last item to the front of the row, one single shift at a time.
Here's how the algorithm would work step-by-step:
def rotate_array_brute_force(elements, step_count):
# Normalize step count to avoid redundant full rotations over the entire list length
normalized_steps = step_count % len(elements)
for current_step in range(normalized_steps):
# Extract the last element because it must be moved to the front during a right shift
last_element = elements[-1]
for current_index in range(len(elements) - 1, 0, -1):
elements[current_index] = elements[current_index - 1]
# Place the extracted element at the front to complete one single rotation step
elements[0] = last_element
return elementsInstead of moving items one by one or making a copy of everything, the optimal approach uses a clever sequence of reversals to rearrange the collection in place. By flipping specific portions of the group and then the whole group, everything naturally lands in its final shifted position.
Here's how the algorithm would work step-by-step:
class Solution:
def rotate(self, collection_items: list[int], shift_distance: int) -> None:
collection_length = len(collection_items)
effective_shift = shift_distance % collection_length
# Normalizing the shift distance ensures we do not perform redundant full-length rotations.
def reverse_subsegment(start_index: int, end_index: int) -> None:
while start_index < end_index:
collection_items[start_index], collection_items[end_index] = collection_items[end_index], collection_items[start_index]
start_index += 1
end_index -= 1
# Reversing the entire collection places the wrapping elements at the front in reversed order.
reverse_subsegment(0, collection_length - 1)
# Reversing the first segment restores the correct internal sequence of the shifted elements.
reverse_subsegment(0, effective_shift - 1)
# Reversing the remaining segment restores the correct internal sequence of the tail elements.
reverse_subsegment(effective_shift, collection_length - 1)| Case | How to Handle |
|---|---|
| k is greater than the length of the array | We take k modulo the array length to avoid redundant full rotations and out of bound errors. |
| k is equal to zero | Modulo operation results in zero, leaving the array completely unchanged as expected. |
| Array contains only a single element | Any value of k results in modulo zero, safely returning the single element array untouched. |
| Empty or null input array | We add an initial guard clause to immediately return before performing any operations. |
| k is a negative number | We add the array length to k after modulo to correctly handle left rotations as equivalent right rotations. |
| Array with maximum constraint length and maximum k value | Using the in-place array reversal algorithm ensures O(1) extra space complexity without memory limit issues. |
| Array containing all identical values | The rotation logic still executes completely, maintaining the identical state of the array seamlessly. |
| Array containing negative numbers and extreme boundary values | The swap and shift operations treat values as opaque elements, preserving their signs and magnitudes. |