Medium
Rotate Array
- Time limit
- 2 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Array Techniques
Description
Description
Given an integer array nums and an integer k, rotate the array to the right by k steps.
Rotating to the right by one step moves the last element to the front and shifts every other element one position to the right. The value k may be larger than the array length; in that case it wraps around.
Return the rotated array.
Examples
Example 1
- Input:
nums = [1, 2, 3, 4, 5, 6, 7],k = 3 - Output:
[5, 6, 7, 1, 2, 3, 4] - Explanation: Rotating right by
3moves5, 6, 7to the front.
Example 2
- Input:
nums = [-1, -100, 3, 99],k = 2 - Output:
[3, 99, -1, -100]
Example 3
- Input:
nums = [1, 2, 3],k = 4 - Output:
Constraints
0 <= nums.length <= 100000-1000000000 <= nums[i] <= 10000000000 <= k <= 100000- Rotations larger than the array length wrap around using modulo.
Sample cases
3Sample 1
Input
k = 3 nums = [1,2,3,4,5,6,7]
Expected output
[5,6,7,1,2,3,4]
Sample 2
Input
k = 2 nums = [-1,-100,3,99]
Expected output
[3,99,-1,-100]
Skills and languages
Concepts
- Arrays
- Modular Arithmetic
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer