Easy
Rotate an Array to the Right
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 15 min
- Array Techniques
Description
Given an integer array nums and a non-negative integer k, rotate the array to the right by k positions.
A right rotation moves the last element to the first position. Elements that move beyond the end wrap around to the beginning. If k is greater than the array length, perform only the equivalent number of rotations using k modulo the array length.
For example, rotating [1, 2, 3, 4, 5] right by 2 positions produces [4, 5, 1, 2, 3]. Rotating by 0 positions leaves the array unchanged.
Implement rotateRight(nums, k) to return the rotated array.
Constraints
1 <= nums.length <= 1000 -1000000 <= nums[i] <= 1000000 0 <= k <= 1000000000 Return an array with the same length and elements as nums.
Sample cases
3Sample 1
Input
k = 2 nums = [1,2,3,4,5]
Expected output
[4,5,1,2,3]
Sample 2
Input
k = 0 nums = [1,2,3]
Expected output
[1,2,3]
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