Skip to the code
+25 XP

#721 Throttle with a Trailing Call

medium

A resize handler is throttled with both edges, so the layout updates right away and also once more after the user stops dragging. The rules:

  • When a call arrives and no cooldown is active, the handler runs at once and a cooldown of wait ms starts.
  • A call during a cooldown doesn't run; it is remembered.
  • When a cooldown ends and a call was remembered, the handler runs at that moment and a new cooldown of wait ms starts. If nothing was remembered, the cooldown just ends.

If a cooldown ends at exactly the time of a call, the cooldown's ending is handled first. Write throttleBothEdges(calls, wait) that returns the times the handler runs. calls is sorted ascending.

Example 1

Input: calls = [0,50,120,130], wait = 100
Output: [0,100,200]

Runs at 0. 50 is remembered and runs when the cooldown ends at 100, starting a new cooldown to 200. 120 and 130 are remembered and run once at 200.

Example 2

Input: calls = [0,300], wait = 100
Output: [0,300]

The calls are far apart, so each runs at once.

Constraints

  • 0 <= calls.length <= 10^5
  • 0 <= calls[i] <= 10^9, sorted ascending.
  • 1 <= wait <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).