Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Rotate Array Right

Working With Arraysmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Implement `rotate(arr, k)` returning a new array rotated to the right by `k` positions. `k` may exceed the array length.

Sample tests

Input: rotate([1,2,3,4,5], 2)
Output: [4,5,1,2,3]
Input: rotate([1,2,3], 0)
Output: [1,2,3]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • k can exceed length, so reduce it with modulo.
  • k of 0 must return the array unchanged, watch slice(-0).

Learning resources

  • MDN: Array
Approach & explanation (try first)

After reducing k modulo length, concatenating the tail of k elements with the head gives a right rotation.

Loading...
⌘/Ctrl + Enter

Run your code to see results.