Rotate Array to the Right
Given an array, rotate the array to the right by k
steps, where k
is a
non-negative integer. The function should modify the input array in-place.
For example, given the array [1, 2, 3, 4, 5, 6, 7]
and k = 3
, the array
should be modified to [5, 6, 7, 1, 2, 3, 4]
.
Function Signature:
from typing import List
def rotate_array(nums: List[int], k: int) -> None:
"""
Rotate the array to the right by k steps.
Parameters:
- nums: List of integers representing the array.
- k: Number of steps to rotate the array.
Returns:
- None: The function should modify the input list in-place.
"""
# Your code here
Example:
nums = [1, 2, 3, 4, 5, 6, 7]
rotate_array(nums, 3)
print(nums)
assert nums == [5, 6, 7, 1, 2, 3, 4], "nums should be [5, 6, 7, 1, 2, 3, 4]"
nums = [-1, -100, 3, 99]
rotate_array(nums, 2)
print(nums)
assert nums == [3, 99, -1, -100], "nums should be [3, 99, -1, -100]"
Note:
- The input array may be of any length, including
0
. - The value of
k
can be greater than the length of the array.
Instructions:
- Write the
rotate_array
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊