Sliding-Window Speaker Count and Peak Utterance Length

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A live speech-processing pipeline receives utterances one by one, where each utterance carries two integers: (user_id, length) — the speaker's identifier and the character count of that utterance.

You need to maintain a sliding window holding at most the K most recent utterances (or every utterance seen so far when fewer than K have arrived). Whenever an utterance enters the window—after evicting the oldest utterance if the window size would exceed K—report two summary statistics over the active window: 1. distinct_users: how many unique user_id values appear at least once inside the window. 2. max_length: the largest length among all utterances currently inside the window.

Implement a stateful TranscriptSummarizer helper (__init__(self, K: int) and add_event(self, user_id: int, length: int) -> Tuple[int, int]) together with the replay entry point transcript_summarizer(operations, arguments):

  • When operations[i] == "init" with arguments[i] == [K], create a fresh summarizer of capacity K and append None to the output list.
  • When operations[i] == "add_event" with arguments[i] == [user_id, length], record the utterance and append [distinct_users, max_length] to the output list.

Return the list of outputs across all operations.

Examples

Example 1

Input:
  operations = ["init", "add_event", "add_event", "add_event", "add_event", "add_event"]
  arguments  = [[3], [10, 12], [20, 30], [10, 8], [30, 25], [40, 18]]

Output:
  [None, [1, 12], [2, 30], [2, 30], [3, 30], [3, 25]]

Explanation: With capacity K = 3: - (10, 12) -> window [(10, 12)]: 1 speaker, max length 12. - (20, 30) -> window [(10, 12), (20, 30)]: 2 speakers, max length 30. - (10, 8) -> window [(10, 12), (20, 30), (10, 8)]: speaker 10 appears twice, so still 2 distinct speakers, max length 30. - (30, 25) -> (10, 12) drops out, leaving [(20, 30), (10, 8), (30, 25)]: speaker 10 still has (10, 8), giving 3 speakers and max length 30. - (40, 18) -> (20, 30) drops out, leaving [(10, 8), (30, 25), (40, 18)]: 3 speakers, and the peak length drops from 30 to 25.

Example 2

Input:
  operations = ["init", "add_event", "add_event", "add_event", "add_event"]
  arguments  = [[2], [5, 14], [5, 6], [8, 4], [8, 11]]

Output:
  [None, [1, 14], [1, 14], [2, 6], [1, 11]]

Explanation: With K = 2, speaker 5 contributes the first two utterances ([1, 14] twice). Adding (8, 4) evicts (5, 14) so the window becomes [(5, 6), (8, 4)] ([2, 6]). Adding (8, 11) evicts (5, 6), leaving only speaker 8 across [(8, 4), (8, 11)] ([1, 11]).

Example 3

Input:
  operations = ["init", "add_event", "add_event", "add_event"]
  arguments  = [[1], [4, 0], [-3, 9], [4, 0]]

Output:
  [None, [1, 0], [1, 9], [1, 0]]

Explanation: When K = 1, each arrival immediately replaces the previous utterance, so distinct_users is always 1 and max_length equals the newest utterance's length (including 0).

Constraints

  • 1 <= K <= 200,000
  • 1 <= len(operations) == len(arguments) <= 200,001 (at most 200,000 "add_event" calls)
  • user_id is a signed integer (-10^15 <= user_id <= 10^15)
  • 0 <= length <= 10^9
  • "init" always appears before the first "add_event" and may appear again later to reset the window.

Step-by-step walkthrough

  1. Understand the sliding window and outputs

    Transcript events (user_id, length) arrive one at a time in a stream. We only care about the sliding window of the most recent K events (or all events seen so far while fewer than K have arrived). After each add_event(user_id, length), we must return two statistics over the current window: 1. distinct_users: how many unique user_id values appear at least once in the window. 2. max_length: the largest length among the events in the window.

    K = 3, events arriving one by one (Example 1):
    
      Step 1: [(10, 12)]                        -> distinct=1, max=12
      Step 2: [(10, 12), (20, 30)]              -> distinct=2, max=30
      Step 3: [(10, 12), (20, 30), (10, 8)]     -> distinct=2, max=30
      Step 4: (10, 12) drops out!
                       [(20, 30), (10, 8), (30, 25)] -> distinct=3, max=30
      Step 5: (20, 30) drops out!
                                [(10, 8), (30, 25), (40, 18)] -> distinct=3, max=25
    

    The judge calls transcript_summarizer(operations, arguments), where "init" passes [K] (outputting None) and "add_event" passes [user_id, length] (outputting [distinct_users, max_length]).

  2. Why rescanning the window each time is too slow

    A straightforward brute force keeps the last K events in a list and calls len(set(...)) and max(...) after every insertion. Each call scans up to K items.

    With N = 200,000 events and K = 200,000, N * K reaches tens of billions of operations — far too slow. Notice why rescanning wastes work: when one new event arrives, K - 1 events in the window stay identical, at most one oldest event leaves, and one new event enters. We need data structures that update both answers incrementally in O(1) time per step.

  3. Track distinct users with a FIFO queue and a frequency map

    Why isn't a plain Python set enough for distinct users? Suppose K = 3 and the window holds user IDs [5, 5, 8]. When a fourth event arrives and the oldest 5 drops out, the remaining window is [5, 8] — user 5 is still inside! Removing 5 from a set would wrongly erase user 5.

    Instead, we combine two structures: - window_users: a deque storing the user_id of each active event from oldest (front) to newest (back), so popleft() tells us in O(1) which user just expired. - user_counts: a dictionary mapping user_id -> count_in_window. Whenever a user's count drops to 0, we del that key so len(user_counts) is always the exact count of distinct users!

    Window (K = 3): [5, 5, 8]    user_counts = {5: 2, 8: 1}  -> len = 2
    Next event: user 12 arrives
      1. append 12       -> window [5, 5, 8, 12], user_counts = {5: 2, 8: 1, 12: 1}
      2. popleft() -> 5  -> decrement 5: {5: 1, 8: 1, 12: 1}  (count is 1 > 0, keep key 5!)
      Result: len(user_counts) = 3
    
  4. Track the maximum length with a monotonic decreasing deque

    How do we maintain max_length as old events expire? Observe what happens when a new event arrives at event_index with length = L:

    Any older event already in the window with length <= L is now completely useless for max_length: 1. While both are in the window, the new event is at least as long (L >= old_length). 2. Because the new event arrived later, it will stay in the window longer than the older event.

    So an older, shorter-or-equal event can never be the window maximum again! We discard such dominated events immediately by maintaining max_deque, a deque of (event_index, length) pairs whose lengths strictly decrease from front to back:

    Back-popping & front-expiry on max_deque:
    
      front (oldest, LARGEST length)               back (newest, SMALLEST length)
      +----------+    +----------+    +----------+
      | (idx, L) | -> | (idx, L) | -> | (idx, L) |
      +----------+    +----------+    +----------+
           ^                               ^
           |                               +-- 1. Pop from BACK while back.length <= new_length,
           |                                      then append (event_index, new_length).
           +-- 2. Pop from FRONT while front.index < event_index - K + 1 (expired!).
               3. Read current window maximum directly at front: max_deque[0][1].
    

    Every event is pushed onto max_deque once and popped at most once across the entire stream, so all deque updates take amortized O(1) time per event.

  5. Implement TranscriptSummarizer and the judge wrapper

    Putting both structures inside TranscriptSummarizer, each add_event assigns a sequential event_index, updates window_users and user_counts, updates max_deque, and returns (distinct_users, max_length). Notice that when fewer than K events have arrived (event_index < K - 1), oldest_valid_index = event_index - K + 1 is negative, so no valid event index (>= 0) is evicted early.

    from typing import Dict, List, Optional, Tuple
    from collections import deque
    
    
    class TranscriptSummarizer:
        def __init__(self, K: int):
            if K <= 0:
                raise ValueError("window size K must be positive")
            self.K = K
            # next_index: sequential ID (0, 1, 2, ...) assigned to each arriving event
            self.next_index = 0
            # window_users: deque of user_id ints currently in the window, oldest at front
            self.window_users: deque = deque()
            # user_counts: dict {user_id: active_count} for users with >= 1 event in the window
            self.user_counts: Dict[int, int] = {}
            # max_deque: deque of (event_index, length) with strictly decreasing lengths;
            # front entry max_deque[0] always holds the maximum length in the current window
            self.max_deque: deque = deque()
    
        def add_event(self, user_id: int, length: int) -> Tuple[int, int]:
            event_index = self.next_index
            self.next_index += 1
    
            # Phase 1: Add the new user_id and evict the oldest user_id if window exceeds K.
            self.window_users.append(user_id)
            self.user_counts[user_id] = self.user_counts.get(user_id, 0) + 1
    
            if len(self.window_users) > self.K:
                oldest_user = self.window_users.popleft()
                self.user_counts[oldest_user] -= 1
                # Delete zero-count keys so len(user_counts) equals distinct active users in O(1).
                if self.user_counts[oldest_user] == 0:
                    del self.user_counts[oldest_user]
    
            # Phase 2: Maintain the monotonic decreasing deque of candidate maximum lengths.
            # Any older event with length <= the new length expires sooner AND is no longer,
            # so it can never be the window maximum again (using <= also deduplicates ties).
            while self.max_deque and self.max_deque[-1][1] <= length:
                self.max_deque.pop()
            self.max_deque.append((event_index, length))
    
            # Phase 3: Evict front candidates whose index fell behind [event_index - K + 1, event_index].
            # Note: max_deque cannot become empty because we just pushed event_index (>= oldest_valid_index).
            oldest_valid_index = event_index - self.K + 1
            while self.max_deque[0][0] < oldest_valid_index:
                self.max_deque.popleft()
    
            distinct_users = len(self.user_counts)
            max_length = self.max_deque[0][1]
            return (distinct_users, max_length)
    
  6. Trace Example 2 step by step

    Let's trace Example 2 with K = 2 and events (5, 14), (5, 6), (8, 4), (8, 11):

    idx=0, add (5, 14), valid indices [-1..0]:
      window_users = [5],       user_counts = {5: 1}
      max_deque    = [(0, 14)]                       -> output [1, 14]
    
    idx=1, add (5, 6), valid indices [0..1]:
      window_users = [5, 5],    user_counts = {5: 2}
      6 < 14 so (0, 14) stays at front
      max_deque    = [(0, 14), (1, 6)]               -> output [1, 14]
    
    idx=2, add (8, 4), valid indices [1..2]:
      window_users = [5, 8] (oldest 5 evicted), user_counts = {5: 1, 8: 1}
      4 < 6 so push (2, 4) -> [(0, 14), (1, 6), (2, 4)]
      front (0, 14) has index 0 < 1 -> expired from front!
      max_deque    = [(1, 6), (2, 4)]                -> output [2, 6]
    
    idx=3, add (8, 11), valid indices [2..3]:
      window_users = [8, 8] (5 evicted -> deleted!), user_counts = {8: 2}
      back (2, 4) and (1, 6) both have length <= 11 -> popped!
      max_deque    = [(3, 11)]                       -> output [1, 11]
    
  7. Assemble the complete solution

    Adding the transcript_summarizer driver completes the solution.

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    
    class TranscriptSummarizer:
        def __init__(self, K: int):
            if K <= 0:
                raise ValueError("window size K must be positive")
            self.K = K
            # next_index: sequential ID (0, 1, 2, ...) assigned to each arriving event
            self.next_index = 0
            # window_users: deque of user_id ints currently in the window, oldest at front
            self.window_users: deque = deque()
            # user_counts: dict {user_id: active_count} for users with >= 1 event in the window
            self.user_counts: Dict[int, int] = {}
            # max_deque: deque of (event_index, length) with strictly decreasing lengths;
            # front entry max_deque[0] always holds the maximum length in the current window
            self.max_deque: deque = deque()
    
        def add_event(self, user_id: int, length: int) -> Tuple[int, int]:
            event_index = self.next_index
            self.next_index += 1
    
            # Phase 1: Add the new user_id and evict the oldest user_id if window exceeds K.
            self.window_users.append(user_id)
            self.user_counts[user_id] = self.user_counts.get(user_id, 0) + 1
    
            if len(self.window_users) > self.K:
                oldest_user = self.window_users.popleft()
                self.user_counts[oldest_user] -= 1
                # Delete zero-count keys so len(user_counts) equals distinct active users in O(1).
                if self.user_counts[oldest_user] == 0:
                    del self.user_counts[oldest_user]
    
            # Phase 2: Maintain the monotonic decreasing deque of candidate maximum lengths.
            # Any older event with length <= the new length expires sooner AND is no longer,
            # so it can never be the window maximum again (using <= also deduplicates ties).
            while self.max_deque and self.max_deque[-1][1] <= length:
                self.max_deque.pop()
            self.max_deque.append((event_index, length))
    
            # Phase 3: Evict front candidates whose index fell behind [event_index - K + 1, event_index].
            # Note: max_deque cannot become empty because we just pushed event_index (>= oldest_valid_index).
            oldest_valid_index = event_index - self.K + 1
            while self.max_deque[0][0] < oldest_valid_index:
                self.max_deque.popleft()
    
            distinct_users = len(self.user_counts)
            max_length = self.max_deque[0][1]
            return (distinct_users, max_length)
    
    
    def transcript_summarizer(
        operations: List[str], arguments: List[List[int]]
    ) -> List[Optional[List[int]]]:
        summarizer: Optional[TranscriptSummarizer] = None
        results: List[Optional[List[int]]] = []
    
        # Replay each operation and convert add_event tuples into the [distinct, max] list format.
        for op, args in zip(operations, arguments):
            if op == "init":
                summarizer = TranscriptSummarizer(args[0])
                results.append(None)
            elif op == "add_event":
                if summarizer is None:
                    raise ValueError("add_event called before init")
                distinct_users, max_length = summarizer.add_event(args[0], args[1])
                results.append([distinct_users, max_length])
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tracking the last K speakers in a live meeting room using two small clipboards: 1. Who is active (distinct_users): You keep a deque (double-ended queue, a list that adds and removes items from either end in O(1) time) of the last K speaker IDs in arrival order, paired with a hash map (a key-value dictionary with O(1) average lookup) counting how many utterances each speaker currently has inside the sliding window (the moving slice of the most recent K events). When a speaker's count drops to 0, you cross them off the dictionary so the dictionary's size is always the number of distinct speakers. 2. Longest utterance (max_length): You keep a monotonic deque (a deque kept sorted from largest to smallest so the front element is always the current maximum). Whenever a new utterance of length L arrives, any older utterance with length <= L can step out of line immediately — it is no longer than the new one and it will expire sooner, so it can never win again!

Why do simpler approaches fall short? Recomputing len(set(window)) and max(window) from scratch on every event scans up to K items per call, taking O(N * K) total time — roughly 2 * 10^10 operations when N = K = 200,000. Using a plain set without counts fails whenever the same user speaks twice inside the window (evicting their first event would wrongly delete them while their second event is still active), and tracking only a single current_max integer fails the moment the longest event slides out of the window and you don't know the runner-up.

Here is how both clipboards work together on K = 3 for events (10, 12), (20, 30), (10, 8), (30, 25), (40, 18):

Event 0: (user=10, len=12)
  window_users = [10],            user_counts = {10: 1}              -> distinct = 1
  max_deque    = [(0, 12)]                                           -> max_len  = 12

Event 1: (user=20, len=30)
  window_users = [10, 20],        user_counts = {10: 1, 20: 1}       -> distinct = 2
  max_deque    = [(1, 30)]        ((0, 12) popped since 12 <= 30)    -> max_len  = 30

Event 2: (user=10, len=8)
  window_users = [10, 20, 10],    user_counts = {10: 2, 20: 1}       -> distinct = 2
  max_deque    = [(1, 30), (2, 8)]                                   -> max_len  = 30

Event 3: (user=30, len=25) -> window exceeds K=3, oldest user 10 (idx 0) leaves:
  window_users = [20, 10, 30],    user_counts = {10: 1, 20: 1, 30: 1} -> distinct = 3
  max_deque    = [(1, 30), (3, 25)] ((2, 8) popped since 8 <= 25; idx 1 >= 1) -> max_len = 30

Event 4: (user=40, len=18) -> oldest user 20 (idx 1) leaves:
  window_users = [10, 30, 40],    user_counts = {10: 1, 30: 1, 40: 1} -> distinct = 3
  max_deque    = [(3, 25), (4, 18)] ((1, 30) expired since idx 1 < 4-3+1=2)   -> max_len = 25

Complexity

Let N be the total number of add_event calls and K be the window size.

  • Time: O(1) amortized per add_event (O(N) total across N events). Appending/popping window_users and updating user_counts take O(1) average time per event. Although the while loop on max_deque can pop several elements during one call, amortized O(1) (meaning the average cost per operation over any sequence of operations is constant) holds because each of the N events is pushed onto max_deque once and popped at most once across the entire run (<= 2N deque operations total).
  • Space: O(min(N, K)) inside TranscriptSummarizer (plus O(N) for the returned results list in the driver). window_users stores at most K user IDs, user_counts stores at most K active keys, and max_deque stores at most K (event_index, length) pairs.

Edge cases

  • Window not yet full (N < K): len(window_users) <= K skips user eviction, and oldest_valid_index = event_index - K + 1 is <= 0 so no entry in max_deque expires early.
  • Window of size K = 1: Every add_event immediately evicts the previous event and returns (1, length) for the newest event alone.
  • Repeated user_id inside the window: A user remains counted until their last event in the window is evicted (user_counts[u] hits 0 and is deleted), and can seamlessly re-enter later.
  • Tied maximum lengths: Using <= when popping from the back replaces an older tie with the newer event at event_index, which expires later and keeps max_length accurate when the older copy slides out.
  • Zero-length transcripts (length = 0) and negative/64-bit user_ids: 0 is handled like any integer length, and Python int keys hash arbitrary signed integers cleanly.

Common mistakes

  • Using a set instead of a frequency map for distinct_users: Evicting (5, 14) from [5, 5, 8] deletes 5 from a set even though another 5 is still inside the window.
  • Forgetting del self.user_counts[oldest_user] when the count reaches 0: Leaving {user_id: 0} entries in the dictionary makes len(self.user_counts) count all historical users rather than active ones.
  • Storing bare lengths (without indices) in max_deque while popping on <=: If two events have length 5 ([5, 5]) and you discard the first 5 via <=, then checking if evicted_length == max_deque[0] when the first 5 leaves the window prematurely pops the second 5! Storing (event_index, length) avoids all ambiguity.
  • Off-by-one on the window boundary: At event_index, a window of size K covers [event_index - K + 1, event_index] (inclusive). Using event_index - K keeps K + 1 events; using len(window) >= K before appending or >= oldest_valid_index when popping keeps only K - 1.

Alternative approaches

  • Max-heap with lazy deletion (O(log N) per event): Push (-length, event_index) onto a max-heap (a binary tree priority queue where the largest value sits at the top, simulated with negated keys in Python's heapq) and use lazy deletion (only popping expired entries from the heap top when they surface). Slightly slower (O(log N) vs O(1) amortized) and can hold up to O(N) stale entries unless periodically compacted, but very quick to code.
  • Two-stack queue (O(1) amortized): Simulate a FIFO queue with an inbox stack and an outbox stack where each stack node stores the running max from the bottom up. This generalizes to any associative operation (like gcd or matrix multiplication) that lacks an inverse, though a monotonic deque is simpler for max.
  • Segment tree over a circular buffer (O(log K) per event): Overwrite slot event_index % K in a segment tree (a binary tree over an array that updates single elements and queries range maxima in logarithmic time); overkill unless arbitrary sub-window queries are also needed.

Follow-up questions

  • How would you adapt the data structures if the window covered a trailing time span (such as the past 30 seconds) rather than the last K events? Store (timestamp, user_id) in window_users and (timestamp, length) in max_deque, and replace the len > K check with while loops at the front of both deques that evict every entry with timestamp <= now - 30 (or < now - 30 if the boundary is inclusive). Although one call can evict many old events at once after a quiet gap, every event still enters and leaves each deque once, preserving O(1) amortized time. If events can arrive slightly out of timestamp order in distributed streams, buffer incoming events briefly up to a watermark (a timestamp threshold behind real time after which late events are rare) before feeding them in chronological order.
  • Does add_event guarantee O(1) time on every single call or only on average, and how could you eliminate worst-case latency spikes? add_event runs in O(1) amortized time (O(N) total across N events), which is asymptotically optimal overall, but a single worst-case call can take O(K) time when a huge length arrives right after K strictly decreasing lengths and pops the entire max_deque at once. If hard real-time tail latency (O(1) worst-case per call) is required, you can use a de-amortized two-stack queue that incrementally transfers one element per arrival, and replace window_users with a pre-allocated ring buffer (a fixed-size array of length K indexed modulo K) to eliminate node allocations.
  • What changes if events arrive in bursts as batches rather than one at a time? First agree on a deterministic ordering within the batch (such as producer sequence number) if callers inspect intermediate per-event outputs, then feed each event through add_event in O(B) total amortized time for a batch of size B. If callers only need the summary after the entire batch finishes and B >= K, you can skip the first B - K events completely and initialize the window from only the last K events in O(K) time! In a multi-threaded service, apply the batch under a single lock or publish an immutable snapshot of (distinct_users, max_length) at the end of the batch so readers never observe half-updated state.

Follow-up questions

Similar questions

More Sesame Ai interview questions

All 1 Sesame Ai questions →