Implement a throttle function with leading and trailing edge behavior
Company: Tencent
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a `Throttler` that rate-limits a function so it executes at most once per fixed time window, with configurable leading and trailing edge behavior.
The throttler is constructed with a window size `wait` (in milliseconds) and two booleans, `leading` and `trailing`. Each call to `invoke(t, value)` provides the current timestamp `t` and a candidate `value`. Depending on the configuration, the throttler either records the value immediately (leading edge), schedules a deferred record at the end of the current window (trailing edge), or discards intermediate calls.
At least one of `leading` or `trailing` must be `True`. When both are enabled, the leading call fires immediately and a trailing call fires only if at least one additional `invoke` occurred during the window. The `flush()` method forces any pending trailing call to execute immediately, and `getCalls()` returns the ordered list of values that have actually been recorded so far.
Implement the following methods:
- `invoke(t: int, value: int) -> int`: process an invocation at timestamp `t` with the given value. Records the value if it falls on the leading edge of a new window (when `leading=True`), or schedules or updates a trailing call (when `trailing=True`). Returns the total number of recorded calls after processing.
- `flush() -> int`: immediately fire any pending trailing call, recording its value. Returns the total number of recorded calls after flushing.
- `getCalls() -> List[int]`: return the ordered list of values that have actually been recorded (executed) so far.
Example 1:
```text
Input:
["Throttler", "invoke", "invoke", "invoke", "invoke", "getCalls", "invoke", "getCalls"]
[[100, true, false], [0, 1], [50, 2], [99, 3], [100, 4], [], [250, 5], []]
Output: [null, 1, 1, 1, 2, [1, 4], 3, [1, 4, 5]]
Explanation:
throttler = Throttler(100, True, False) # wait = 100 ms, leading only
throttler.invoke(0, 1) # 1 leading edge, records 1
throttler.invoke(50, 2) # 1 inside the window, dropped
throttler.invoke(99, 3) # 1 inside the window, dropped
throttler.invoke(100, 4) # 2 new window at t = 100, records 4
throttler.getCalls() # [1, 4]
throttler.invoke(250, 5) # 3 new window at t = 250, records 5
throttler.getCalls() # [1, 4, 5]
```
Example 2:
```text
Input:
["Throttler", "invoke", "invoke", "invoke", "invoke", "getCalls", "flush", "getCalls"]
[[100, true, true], [0, 1], [40, 2], [80, 3], [99, 4], [], [], []]
Output: [null, 1, 1, 1, 1, [1], 2, [1, 4]]
Explanation:
throttler = Throttler(100, True, True) # wait = 100 ms, leading and trailing
throttler.invoke(0, 1) # 1 leading edge, records 1, window [0, 100)
throttler.invoke(40, 2) # 1 in the window, pending trailing = 2 at t = 100
throttler.invoke(80, 3) # 1 pending trailing becomes 3
throttler.invoke(99, 4) # 1 pending trailing becomes 4
throttler.getCalls() # [1]
throttler.flush() # 2 fires the pending trailing call, 4
throttler.getCalls() # [1, 4]
```
```hint State to keep
Very little state is needed. Decide which single timestamp defines the current window, and what a pending trailing call has to remember.
```
```hint No timers
Nothing runs between calls, so a trailing call that should already have fired has to be dealt with when the next `invoke` arrives. Check what firing it does to the window that the new call falls into.
```
### Constraints & Assumptions
- `1 <= wait <= 10⁶` (milliseconds)
- `0 <= t <= 10⁹`, and timestamps are non-decreasing across calls
- At least one of `leading` or `trailing` is `True`
- `-10⁹ <= value <= 10⁹`
- At most `10⁴` total operations
- There is no background timer. A trailing call that has come due is recorded by the next `invoke` (before that call is processed) or by `flush`.
### Clarifying Questions to Ask
- After a trailing call fires, does the next window start at the trailing call's scheduled time or at the timestamp of the call that came after it?
- `flush` takes no timestamp. Should the flushed call count as executed at its scheduled time or at the latest timestamp seen so far?
- In trailing-only mode, does a window open at the first call after a quiet period?
- Will the throttler be called from more than one thread?
### What a Strong Answer Covers
- The state the throttler needs: where the current window starts, the pending trailing value and its due time, and the recorded list.
- Correct behavior in all three modes (leading only, trailing only, both), including that in "both" mode a trailing call needs an extra call inside the window.
- Settling an overdue trailing call at the start of `invoke` before deciding whether the new call opens a window.
- A stated rule for where the next window starts after a trailing call or a `flush`, applied the same way everywhere.
- Boundary cases such as calls exactly `wait` apart, repeated timestamps and `flush` with nothing pending, plus the cost of each method.
### Follow-up Questions
- How would you build the same behavior with real timers, and what would a `cancel()` method have to reset?
- How does a debouncer differ from this throttler, and what would you change in the code to turn one into the other?
- How would you make the throttler safe when `invoke` is called from several threads?
- How would you throttle per key, such as per user, without keeping state for idle keys forever?
Overview: Implement a throttler that lets a function run at most once per fixed time window, with options to fire on the leading edge, the trailing edge or both, plus a flush operation. It tests careful state tracking, window boundaries and simulated timers in a low-level design setting.