Rotating Chore Chart

Mediumtwo pointersAlso known as Rotate Array

Your shared house has a chore chart: a fixed list of chores and one name beside each. Every week the names move down one place, and whoever falls off the bottom wraps to the top.

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

Your task

Write rotateChores(names, k). Move every name k places towards the end, 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 wrap to the top, in the same order.

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

Moving 3 places brings everyone back, 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, by moving the last name to the front and shifting everyone else down.

Each one-place rotation moves all n names, so this costs n × k steps, and with 100,000 names and k in the billions it never finishes. Reducing k to k % n still leaves up to n² moves. Copying into a new list takes O(n) time but needs 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