JavaScriptMediumArrays20 min
Rotate an array to the right
Rotate an integer array right by k positions; k may exceed the array length. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess reduce the rotation modulo the length and concatenate two slices.
Input
A JSON object {"array": [...], "k": integer}.
Output
Print one compact JSON value: the rotated array.
Constraints
0 <= array length <= 10000; 0 <= k <= 1000000000; integer values between -1000000 and 1000000.
Example
Input
{"array":[1,2,3,4,5],"k":2}Output
[4,5,1,2,3]
Example 2 input
{"array":[1,2],"k":1000000000}Output
[1,2]
Boundary case: Handle the empty array before taking a remainder
Public test cases (2)
Input
{"array":[1,2,3,4,5],"k":2}Expected output
[4,5,1,2,3]
Input
{"array":[1,2,3],"k":4}Expected output
[3,1,2]
Hints (2)
- Separate the suffix that moves to the front
- Handle the empty array before taking a remainder
Target complexity: time O(n) · space O(n)
