Snowflake questions

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 timestamp ts and key key. Returns nothing. When the window already holds m events, the oldest arrival leaves first.
  • distinct() returns how many different keys are currently in the window, 0 when it is empty.
  • top() returns the key with the highest count in the window, breaking ties by the lexicographically smallest key, or None when the window is empty.
  1. 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, after x, y, x the window has two distinct keys and x leads with count 2. Adding z evicts the first x; y, x, z are all tied at 1, so the smallest key x wins. A second z makes z the leader. A third z evicts x, leaving z, z, z with one distinct key.

Constraints

  • 1 <= m <= 10^4
  • 1 <= len(operations) <= 10^4
  • 0 <= ts <= 10^9, non-decreasing across add calls
  • 1 <= len(key) <= 10
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question