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"witharguments[i] == [K], create a fresh summarizer of capacityKand appendNoneto the output list. - When
operations[i] == "add_event"witharguments[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,0001 <= len(operations) == len(arguments) <= 200,001(at most200,000"add_event"calls)user_idis 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
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 recentKevents (or all events seen so far while fewer thanKhave arrived). After eachadd_event(user_id, length), we must return two statistics over the current window: 1.distinct_users: how many uniqueuser_idvalues appear at least once in the window. 2.max_length: the largestlengthamong 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=25The judge calls
transcript_summarizer(operations, arguments), where"init"passes[K](outputtingNone) and"add_event"passes[user_id, length](outputting[distinct_users, max_length]).Why rescanning the window each time is too slow
A straightforward brute force keeps the last
Kevents in a list and callslen(set(...))andmax(...)after every insertion. Each call scans up toKitems.With
N = 200,000events andK = 200,000,N * Kreaches tens of billions of operations — far too slow. Notice why rescanning wastes work: when one new event arrives,K - 1events 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 inO(1)time per step.Track distinct users with a FIFO queue and a frequency map
Why isn't a plain Python
setenough for distinct users? SupposeK = 3and the window holds user IDs[5, 5, 8]. When a fourth event arrives and the oldest5drops out, the remaining window is[5, 8]— user5is still inside! Removing5from asetwould wrongly erase user5.Instead, we combine two structures: -
window_users: adequestoring theuser_idof each active event from oldest (front) to newest (back), sopopleft()tells us inO(1)which user just expired. -user_counts: a dictionary mappinguser_id -> count_in_window. Whenever a user's count drops to0, wedelthat key solen(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) = 3Track the maximum length with a monotonic decreasing deque
How do we maintain
max_lengthas old events expire? Observe what happens when a new event arrives atevent_indexwithlength = L:Any older event already in the window with length
<= Lis now completely useless formax_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, adequeof(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_dequeonce and popped at most once across the entire stream, so all deque updates take amortizedO(1)time per event.Implement TranscriptSummarizer and the judge wrapper
Putting both structures inside
TranscriptSummarizer, eachadd_eventassigns a sequentialevent_index, updateswindow_usersanduser_counts, updatesmax_deque, and returns(distinct_users, max_length). Notice that when fewer thanKevents have arrived (event_index < K - 1),oldest_valid_index = event_index - K + 1is 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)Trace Example 2 step by step
Let's trace Example 2 with
K = 2and 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]Assemble the complete solution
Adding the
transcript_summarizerdriver 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 peradd_event(O(N)total acrossNevents). Appending/poppingwindow_usersand updatinguser_countstakeO(1)average time per event. Although thewhileloop onmax_dequecan pop several elements during one call, amortizedO(1)(meaning the average cost per operation over any sequence of operations is constant) holds because each of theNevents is pushed ontomax_dequeonce and popped at most once across the entire run (<= 2Ndeque operations total). - Space:
O(min(N, K))insideTranscriptSummarizer(plusO(N)for the returnedresultslist in the driver).window_usersstores at mostKuser IDs,user_countsstores at mostKactive keys, andmax_dequestores at mostK(event_index, length)pairs.
Edge cases
- Window not yet full (
N < K):len(window_users) <= Kskips user eviction, andoldest_valid_index = event_index - K + 1is<= 0so no entry inmax_dequeexpires early. - Window of size
K = 1: Everyadd_eventimmediately evicts the previous event and returns(1, length)for the newest event alone. - Repeated
user_idinside the window: A user remains counted until their last event in the window is evicted (user_counts[u]hits0and 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 atevent_index, which expires later and keepsmax_lengthaccurate when the older copy slides out. - Zero-length transcripts (
length = 0) and negative/64-bituser_ids:0is handled like any integer length, and Pythonintkeys hash arbitrary signed integers cleanly.
Common mistakes
- Using a
setinstead of a frequency map fordistinct_users: Evicting(5, 14)from[5, 5, 8]deletes5from a set even though another5is still inside the window. - Forgetting
del self.user_counts[oldest_user]when the count reaches0: Leaving{user_id: 0}entries in the dictionary makeslen(self.user_counts)count all historical users rather than active ones. - Storing bare lengths (without indices) in
max_dequewhile popping on<=: If two events have length5([5, 5]) and you discard the first5via<=, then checkingif evicted_length == max_deque[0]when the first5leaves the window prematurely pops the second5! Storing(event_index, length)avoids all ambiguity. - Off-by-one on the window boundary: At
event_index, a window of sizeKcovers[event_index - K + 1, event_index](inclusive). Usingevent_index - KkeepsK + 1events; usinglen(window) >= Kbefore appending or>= oldest_valid_indexwhen popping keeps onlyK - 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'sheapq) and use lazy deletion (only popping expired entries from the heap top when they surface). Slightly slower (O(log N)vsO(1)amortized) and can hold up toO(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 runningmaxfrom the bottom up. This generalizes to any associative operation (likegcdor matrix multiplication) that lacks an inverse, though a monotonic deque is simpler formax. - Segment tree over a circular buffer (
O(log K)per event): Overwrite slotevent_index % Kin 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)inwindow_usersand(timestamp, length)inmax_deque, and replace thelen > Kcheck withwhileloops at the front of both deques that evict every entry withtimestamp <= now - 30(or< now - 30if 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, preservingO(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_eventguarantee O(1) time on every single call or only on average, and how could you eliminate worst-case latency spikes?add_eventruns inO(1)amortized time (O(N)total acrossNevents), which is asymptotically optimal overall, but a single worst-case call can takeO(K)time when a hugelengtharrives right afterKstrictly decreasing lengths and pops the entiremax_dequeat 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 replacewindow_userswith a pre-allocated ring buffer (a fixed-size array of lengthKindexed moduloK) 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_eventinO(B)total amortized time for a batch of sizeB. If callers only need the summary after the entire batch finishes andB >= K, you can skip the firstB - Kevents completely and initialize the window from only the lastKevents inO(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
- 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?
- Does `add_event` guarantee O(1) time on every single call or only on average, and how could you eliminate worst-case latency spikes?
- What changes if events arrive in bursts as batches rather than one at a time?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array