Rotate Array

Medium~15 min

Given an array of integers nums and a non-negative integer k, rotate the array to the right by k steps and return the result.

Rotating to the right by 1 step means the last element moves to the front. When k is greater than or equal to the array length, use k % length to determine the effective rotation.

For example, [1, 2, 3, 4, 5] rotated by 2 becomes [4, 5, 1, 2, 3].

Examples

Example 1
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
Explanation: The last 2 elements [4, 5] move to the front.
Example 2
Input: nums = [1, 2, 3], k = 4
Output: [3, 1, 2]
Explanation: k=4 with length 3 means effective rotation is 4 % 3 = 1 step.
Example 3
Input: nums = [1, 2, 3], k = 0
Output: [1, 2, 3]
Explanation: No rotation needed when k is 0.

Constraints

  • 0 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^5
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run