Box Office Withdrawal Waves

Find each position's removal round under simultaneous run deletions

HardLinked ListSimulationRun Compression

A theater box office keeps reservation slips in a singly linked list. Each node's integer value is the campaign code printed on that slip.

The office repeatedly applies the following withdrawal round:

  1. Examine the list as it stands at the start of the round.
  2. Identify every maximal consecutive run of equal campaign codes whose length is at least threshold.
  3. Remove all slips in all such runs simultaneously, preserving the order of the remaining slips.

A maximal run cannot be extended to the left or right with another slip of the same code. Removing runs may bring equal codes together. Any newly formed run must wait until the next round before it can be removed.

Rounds are numbered starting at 1. The process stops when no run qualifies.

Given the list's head and threshold, return an integer array in the list's original order. For each original node, report the round in which it was removed, or 0 if it remains when the process stops. Return an empty array for an empty list.

Examples

Example 1

Input: head = [9,4,7,7,4], threshold = 2
Output: [0,2,1,1,2]

In round 1, the two adjacent slips with code 7 are removed. The two slips with code 4 then become adjacent and are removed in round 2. The slip with code 9 remains.

Example 2

Input: head = [1,3,3,5,5,1], threshold = 2
Output: [2,1,1,1,1,2]

The runs of code 3 and code 5 both qualify at the start of round 1, so both disappear in that round. Their removal joins the two code-1 slips, which disappear in round 2.

Example 3

Input: head = [2,2,8], threshold = 3
Output: [0,0,0]

With a threshold of 3, neither the two code-2 slips nor the single code-8 slip qualify. Every slip remains.

Constraints

  • The list contains between 0 and 100000 nodes.
  • -1000000000 <= Node.val <= 1000000000
  • 2 <= threshold <= 100000

An O(n)-time, O(n)-auxiliary-space solution is expected. Repeatedly scanning the entire surviving list can take quadratic time. The input list does not need to be modified.

Hints

Show hint 1

Compress the initial list into maximal equal-value runs. Maintain predecessor and successor links between surviving runs.

Show hint 2

Separate each round into removal and merging phases. After all scheduled runs are removed, only newly exposed boundaries can create candidates for the next round.

Follow-up questions

What an interviewer might ask once you have a working solution.

  • Can you also return the final surviving linked list without allocating replacement nodes?
  • How would you adapt the algorithm if each campaign code had its own fixed removal threshold?

Practice this with an AI interviewer

Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.

Start this problem