Rotate the Carousel

MediumArrays & Hashing

Problem

A homepage carousel shows its slides in the order stored in slides. Every tick, each slide moves one position to the right and the last slide wraps around to the front.

Given the number of ticks k, rotate slides to the right by k positions in place with O(1) extra space. The function returns nothing.

Example 1

Input:
slides = [1, 2, 3, 4, 5], k = 2
Output:
[4, 5, 1, 2, 3]

After two ticks, 4 and 5 have wrapped to the front.

Example 2

Input:
slides = [10, 20, 30], k = 4
Output:
[30, 10, 20]

Four ticks on three slides equal one tick.

Constraints

  • 1 ≤ slides.length ≤ 10^5
  • -2^31 ≤ slides[i] ≤ 2^31 - 1
  • 0 ≤ k ≤ 10^9

Hint

Show the first hint

First reduce k: rotating by n positions changes nothing.

Walkthrough

How to approach it

01Clarify before coding

  • Can k exceed the length? Yes, up to 10^9; only k mod n matters.
  • Right rotation means the last element moves to the front? Yes.
  • Is an O(n) copy allowed? No, the target is O(1) extra space.

02Brute force

Repeat k times: save the last element, shift everything right by one, put the saved element at index 0.

Cost: O(n · k) time, up to 10^5 × 10^5 after reducing k: far too slow. Copying into a new array is O(n) time but O(n) space.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.