Engineering platform~40 min2s · 256 MBtarget O(n) time, O(1) spacebit-manipulation
A build pipeline has n stages in a row. Stage 1 is the last one before release, and stages[i] jobs wait at stage i + 1. Two engineers play a game on this board and take turns.
A move picks a stage that has jobs and moves any positive number of them one stage closer to release. From stage 1, the jobs are released and leave the board. An engineer who cannot move loses. Your team lead asks: "How many first moves leave the other engineer losing?"
Write count_winning_moves(stages).
stages[i] is the number of jobs at stage i + 1, and stage 1 is the closest to release.k, with 1 ≤ k ≤ the jobs at that stage. It moves k jobs from that stage to the one before it, or out of the board from stage 1.0 when no such move exists.Input: stages = [2, 3, 4, 1]
Output: 2Only the stages 1 and 3 (the odd ones) behave like piles of an ordinary Nim game. Their xor is 2 xor 4 = 6. For each stage:
| Stage | Jobs | Winning move | Why |
|---|---|---|---|
| 1 | 2 | none | 2 xor 6 = 4, which is not smaller than 2 |
| 2 | 3 | move 2 jobs to stage 1 | stage 1 becomes 4, and 4 xor 4 = 0 |
| 3 | 4 | move 2 jobs to stage 2 | stage 3 becomes 2, and 2 xor 2 = 0 |
| 4 | 1 | none | stage 3 would have to shrink to 2, but a move only adds to it |
So there are 2 winning first moves.
Input: stages = [1, 1]
Output: 1Moving the job of stage 1 out of the board leaves one job at stage 2. The second engineer must move it to stage 1, and the first engineer then releases it.
Input: stages = [0, 5]
Output: 0The odd stages hold 0 jobs, so the xor is 0. Whatever the first engineer does, the second engineer can answer.
1 ≤ len(stages) ≤ 100,0000 ≤ stages[i] ≤ 1,000,000,000The number of positions of the board grows exponentially with the number of stages, so no search can work. The answer has to come from a rule that looks at each stage once. A rule built on xor takes one pass over the stages.