Ctrl K

Roll an Array to the Right

Medium
You are given an integer array values and an integer k ≥ 0. Roll the array to the right by k positions, wrapping around: in one step the last element moves to the front and all the others shift one place to the right. Return the rolled array. There are several ways to solve this. Try to use only O(1) extra memory.
Example 1
values=[4, 8, 15, 16, 23], k=2 → [16, 23, 4, 8, 15]

The last two elements move to the front: the result is [16, 23, 4, 8, 15].

Example 2
values=[1, 2, 3], k=4 → [3, 1, 2]

Shifting by 3 brings the array back to where it started, so shifting by 4 is the same as by 1: [3, 1, 2].

Example 3
values=[-5, 9], k=0 → [-5, 9]

There is no shift, so the array stays the same.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • -2³¹ ≤ values[i] ≤ 2³¹ - 1
  • 0 ≤ k ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSorted Parabola Values MediumEnd Stones Close Ranks MediumSquare Equals a Pair Product MediumWord Topping Duel HardTwo Boards Holding Water Medium
loading Python…
Input
values=[4, 8, 15, 16, 23], k=2
Expected
[16, 23, 4, 8, 15]

Run checks the first 3 tests in your browser. Submit checks all 35 tests on the server, hidden ones included.