Katkat

Summarize Transcript Events in a Sliding Window

Sesame AiSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to maintain window-based statistics using an efficient data structure, specifically focusing on tracking counts of distinct elements and the maximum value in a sliding window.

Problem Statement

You are processing a stream of transcript events where each event is represented by a tuple (user_id, length). As these events arrive, you need to maintain a sliding window of the last K events. After each new event is added to the window, return a result containing the current number of distinct user_ids and the maximum length within that window.

Implement the class TranscriptSummarizer:

  • __init__(self, K: int): Initializes the object with the window size K.
  • add_event(self, user_id: int, length: int) -> Tuple[int, int]: Adds the event to the window. If the window exceeds size K, the oldest event is removed. Returns a tuple (distinct_users, max_length).

Constraints

  • 1 <= K <= 200,000
  • Total number of events N <= 200,000
  • user_id is an integer.
  • length is a non-negative integer.

Example

# K = 3
s = TranscriptSummarizer(3)
s.add_event(1, 10) # Window: [(1, 10)], Output: (1, 10)
s.add_event(2, 20) # Window: [(1, 10), (2, 20)], Output: (2, 20)
s.add_event(1, 5)  # Window: [(1, 10), (2, 20), (1, 5)], Output: (2, 20)
s.add_event(3, 15) # Window: [(2, 20), (1, 5), (3, 15)], Output: (3, 20)

Edge Cases

  • The window is not yet full (N < K).
  • Repeated user_ids being added and removed.
  • All length values are the same.

Hints

Hint 1

To track distinct users efficiently, use a hash map (dictionary) to store the frequency of each `user_id` in the current window.

Hint 2

To find the maximum length in a sliding window, consider using a monotonic deque (double-ended queue) to keep track of length indices in descending order.

Hint 3

Ensure that when an event is removed from the window, you update both the frequency map (decrementing user count) and the monotonic deque (removing indices that are no longer in the range).

Follow-up questions

  • How would your implementation change if the window was based on a time duration (e.g., the last 60 seconds) instead of a fixed number of events?
  • What is the time complexity of your `add_event` method, and can it be optimized further?
  • How would you handle a scenario where multiple events arrive simultaneously and need to be processed as a batch?