KatInterview

Per-Key Cooldown Filter for a Timestamped Event Feed

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designhash-mapsimulationrate-limiting

Last updated

Walk a time-ordered event feed and decide which events pass a 10-second per-key cooldown, where only accepted events restart the cooldown.

Per-Key Cooldown Filter for a Timestamped Event Feed

A notification service receives a feed of events. Each event has a text label and the time (in whole seconds) at which it arrived. To avoid flooding the output, the service lets an event through only if its label has not already been let through within the last 10 seconds.

You are given two parallel lists, timestamps and messages, that describe the feed in arrival order. Return a list of booleans saying, for every event, whether it is let through (True) or dropped (False).

Rules

  • Event i has arrival time timestamps[i] and label messages[i]. Process events in the given order.
  • The first event with a given label is always let through.
  • Suppose a label was most recently let through at time t. A later event with the same label is let through only if its time is at least t + 10. A gap of exactly 10 seconds is enough.
  • Only events that are let through affect the cooldown. A dropped event does not restart or extend the cooldown of its label.
  • Different labels are completely independent. Several events may have the same timestamp.
  • Two labels are the same only if the strings are exactly identical.
  • The returned list has the same length as the input. Entry i is True if event i is let through and False otherwise.

Constraints

  • 1 <= len(timestamps) == len(messages) <= 10^4
  • 0 <= timestamps[i] <= 10^9, and timestamps is non-decreasing
  • 1 <= len(messages[i]) <= 30
  • Each label consists only of lowercase English letters and digits

Examples

Example 1

Input: filter_events_by_cooldown([0, 4, 9, 10, 10, 15], ['disk', 'cpu', 'disk', 'disk', 'cpu', 'cpu'])

Output: [True, True, False, True, False, True]

Example 2

Input: filter_events_by_cooldown([5, 12, 15], ['a', 'a', 'a'])

Output: [True, False, True]

Hints

Hint 1

Each label needs only a single remembered value. Think about what that value should be.

Hint 2

Store the time at which each label was last let through, not the time it was last seen. What should happen to that stored value when an event is dropped?

Hint 3

Use a dictionary from label to last accepted time. An event passes if the label is missing or its time is at least the stored time plus 10; update the dictionary only when it passes.