Rotate Array

Medium#189towards each other

You get an array of numbers and a number k. Shift the array k places to the right in a circle: the numbers that fall off the end come back at the start. Do it inside the same array, without a second one. Our example: [1, 2, 3, 4, 5, 6], k = 2 → [5, 6, 1, 2, 3, 4].

input
nums: integers; k: how many steps to turn them by.
returns
Nothing: turn nums in place k steps to the right, so that the last number moves to the front k times over. k may be larger than the length.
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • 0 ≤ k ≤ 10⁵
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
function rotate(nums, k) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.