Recent Event Window
SnowflakePhone screenMedium
You are given a stream of events, each a timestamp ts and a string key key, processed by an EventWindow(m). Timestamps arrive in non-decreasing order and may repeat. The window keeps only the m most recent arrivals: when an event arrives and the window already holds m events, the oldest arrival leaves, regardless of its timestamp. When several keys are equally frequent, the lexicographically smallest key is the answer. Each test drives one EventWindow through a sequence of calls and checks every return value; the constructor's return is not recorded.
Part 1: Distinct and most frequent
Implement an event window that keeps the m most recent events.
add(ts, key)records an event with timestamptsand keykey. Returns nothing. When the window already holdsmevents, the oldest arrival leaves first.distinct()returns how many different keys are currently in the window,0when it is empty.top()returns the key with the highest count in the window, breaking ties by the lexicographically smallest key, orNonewhen the window is empty.
- Example 1
- init
[3]- operations
[["top",[]],["distinct",[]],["add",[1,"x"]],["add",[2,"y"]],["add",[3,"x"]],["distinct",[]],["top",[]],["add",[4,"z"]],["distinct",[]],["top",[]],["add",[5,"z"]],["top",[]],["add",[6,"z"]],["distinct",[]],["top",[]]]- Output
[null,0,null,null,null,2,"x",null,3,"x",null,"z",null,1,"z"]
Why: With
m = 3, afterx,y,xthe window has two distinct keys andxleads with count 2. Addingzevicts the firstx;y,x,zare all tied at 1, so the smallest keyxwins. A secondzmakeszthe leader. A thirdzevictsx, leavingz,z,zwith one distinct key.
Constraints
1 <= m <= 10^41 <= len(operations) <= 10^40 <= ts <= 10^9, non-decreasing acrossaddcalls1 <= len(key) <= 10