Rotating Chore Chart

Mediumtwo pointersAlso known as Rotate Array

Your shared house has a chore chart: a fixed list of chores (dishes, bins, bathroom, vacuuming, shopping) and a list of names beside it, one name per chore. To keep things fair, the names move down the chart every week. Whoever falls off the bottom wraps around to the top.

After a holiday the chart is several weeks behind. You want to move the names down by that many places in one go, rewriting the list you already have rather than making a new chart.

Your task

Write rotateChores(names, k). Move every name k places towards the end of the list, wrapping around: the name at index i ends up at index (i + k) % names.length.

Change names in place and return nothing. k can be larger than the list, and the list can be empty. Try to use only O(1) extra memory.

rotateChores(names: string[], k: int) → void (changes names in place)

Examples

Example 1
Input
names = ["Ana", "Ben", "Caro", "Dev", "Eli"]
k = 2
Output
["Dev", "Eli", "Ana", "Ben", "Caro"]
Why

Everyone moves down 2 places. Dev and Eli fall off the bottom and wrap to the top, in the same order they were in.

Example 2
Input
names = ["Ana", "Ben", "Caro"]
k = 7
Output
["Caro", "Ana", "Ben"]
Why

Moving 3 places brings everyone back where they started, so 7 places is the same as 7 % 3 = 1 place. Caro wraps to the top.

Constraints

  • 0 ≤ names.length ≤ 100,000
  • 0 ≤ k ≤ 1,000,000,000
  • Names are non-empty strings and may repeat.
Start with brute force

Rotate by one place, k times: take the last name off and put it at the front, shifting everyone else down.

Each one-place rotation moves all n names, so this costs n × k steps. With 100,000 names and k in the billions it never finishes. Reducing k to k % n helps, but it is still up to n² moves. Copying into a new list is fast, O(n), but uses a second list of n names.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code