KatInterview

Circular Lamps with Traveling Togglers

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingdifference-arraymodular-arithmeticparity

Last updated

Find the final bits on a ring after several togglers walk clockwise for k steps, using lap decomposition, parity, and a cyclic difference array.

Circular Lamps with Traveling Togglers

A ring has n lamps, numbered 0 to n - 1 clockwise. After lamp n - 1 comes lamp 0. Each lamp is either off (0) or on (1), and colors gives the starting states.

You are also given a list markers of starting positions for m togglers. Several togglers may start on the same lamp. You are also given an integer k, the number of rounds to run.

Each round has two phases:

  1. Every toggler flips the lamp it is standing on. A lamp hosting t togglers is flipped t times in this phase, so it changes state only if t is odd.
  2. Then all togglers move one lamp clockwise at the same time. A toggler on lamp p moves to lamp (p + 1) % n.

Run exactly k rounds and return the final state of all n lamps as a list. Do not modify the input list.

If k = 0, nothing happens and the result equals colors.

Constraints

  • 1 <= n <= 100,000
  • len(colors) == n, and each colors[i] is 0 or 1
  • 1 <= len(markers) <= 100,000
  • 0 <= markers[i] < n
  • k is a non-negative integer that can be very large (up to about 10^18), so simulating round by round is too slow
  • The return value is a list of n integers, each 0 or 1

Examples

Example 1

Input: toggle_ring_lamps(4, [0, 0, 0, 0], [0, 2], 3)

Output: [0, 1, 0, 1]

Example 2

Input: toggle_ring_lamps(5, [1, 0, 1, 1, 0], [1], 5)

Output: [0, 1, 0, 0, 1]

Hints

Hint 1

After n rounds a single toggler has stood on every lamp exactly once. Write k = q * n + r and treat the q full laps separately from the leftover r rounds.

Hint 2

Only the parity of the number of flips per lamp matters. Full laps flip every lamp q * m times in total, so they invert everything only if q and m are both odd.

Hint 3

In the leftover r rounds (r < n), a toggler starting at p flips the cyclic range p, p+1, ..., p+r-1. Count how many ranges cover each lamp with a difference array, splitting ranges that wrap past n-1, then take each count mod 2.