Rotate an Array Right (Set 9)

Medium

Given an array of integers nums and a whole number k, rotate the array to the right by k positions and return the result.

k may be larger than the array; rotating by nums.length is a no-op.

Rotate an Array Right (Set 9) — the data. This set runs 4 cases: nums holds arrays of 41–46 items, with values from -20 to 20; k ranges over 0–39. The hidden cases are the largest of the set.

Example 1

rotateArrayRight()
Input
nums = [-20, -9, 10, -17, 2, 16, 8, -14, -6, 16, -4, 6, -1, -3, 15, 5, 5, 16, -2, 5, -7, -17, 20, 20, -5, 4, -15, -9, -4, 16, -12, -14, -9, -18, 2, -2, 17, 10, 20, 10, 2], k = 19
Output
[20, 20, -5, 4, -15, -9, -4, 16, -12, -14, -9, -18, 2, -2, 17, 10, 20, 10, 2, -20, -9, 10, -17, 2, 16, 8, -14, -6, 16, -4, 6, -1, -3, 15, 5, 5, 16, -2, 5, -7, -17]

Why

`rotateArrayRight` returns `[20, 20, -5, 4, -15, -9, -4, 16, -12, -14, -9, -18, 2, -2, 17, 10, 20, 10, 2, -20, -9, 10, -17, 2, 16, 8, -14, -6, 16, -4, 6, -1, -3, 15, 5, 5, 16, -2, 5, -7, -17]` for this input.

Example 2

rotateArrayRight()
Input
nums = [0, -14, 12, -16, -17, -6, -3, -14, -11, 6, 15, -4, 3, 12, 0, 4, -2, -20, -12, 4, -19, 14, -5, 15, 13, -6, -4, 8, 4, -13, 19, -8, 3, 15, 15, 10, 18, -19, 4, -9, -1, 8, -1, -11, 0, 6], k = 0
Output
[0, -14, 12, -16, -17, -6, -3, -14, -11, 6, 15, -4, 3, 12, 0, 4, -2, -20, -12, 4, -19, 14, -5, 15, 13, -6, -4, 8, 4, -13, 19, -8, 3, 15, 15, 10, 18, -19, 4, -9, -1, 8, -1, -11, 0, 6]

Why

`rotateArrayRight` returns `[0, -14, 12, -16, -17, -6, -3, -14, -11, 6, 15, -4, 3, 12, 0, 4, -2, -20, -12, 4, -19, 14, -5, 15, 13, -6, -4, 8, 4, -13, 19, -8, 3, 15, 15, 10, 18, -19, 4, -9, -1, 8, -1, -11, 0, 6]` for this input.
Constraints
0 <= nums.length <= 10^4
0 <= k <= 10^6
Every case in this set must pass: the first two are visible on Run, the last two unlock on Submit.

Topics

ArraysTwo Pointers

Implement rotateArrayRight in the editor and return the answer — printing it is never graded.