Fix the debounce replay on a virtual clock

Review the AI's codeEasy12 min

Your task

Your search box debounces its queries: it waits until typing pauses for a set time, then runs only the latest call. An agent fixed a flaky debounce test by adding a real sleep, so the team now checks the debounce on a virtual clock instead.

An assistant wrote debounce_calls(events, wait_ms). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • events: the calls to the debounced function, in the order they were made. Each is "<time_ms>|<arg>": the virtual time of the call in milliseconds, then its argument.
  • wait_ms: the debounce wait in milliseconds. An integer, and it can be 0 or negative.
  • Return the arguments of the calls that actually run, in order.

Rules the tests check:

  • Split an event at its first |. The time is the part before it and must be 1 to 9 digits (0 to 9 only). The argument is the rest. It can be empty and can contain |.
  • Skip an event with no | or with a bad time. Skipped events play no part in anything below.
  • The clock never runs backwards. If a kept event's time is less than the time used for the kept event before it, use that previous time instead.
  • A wait below 0 counts as 0.
  • Each call starts its own timer, set to its time plus the wait. When the next kept call comes before that timer fires, the call is cancelled and never runs.
  • So a call runs when the next kept call comes at or after its time plus the wait. A timer set for exactly the time of the next call has already fired, so that call runs. With a wait of 0, every call runs.
  • The last kept call always runs: the clock is run to the end.
  • No kept events returns an empty list.

Examples

debounce_calls(events: list[str], wait_ms: int) -> list[str]
Example 1
Inputdebounce_calls(["0|a", "100|ab", "200|abc"], 300)
Output["abc"]
Example 2
Inputdebounce_calls(["0|a", "300|b"], 300)
Output["a", "b"]
Example 3
Inputdebounce_calls(["0|a", "299|b"], 300)
Output["b"]