Summarize a Stream of Event IDs as Disjoint Ranges
Last updated: November 29, 2026
Quick Overview
Event IDs arrive one at a time, possibly out of order and with duplicates. Implement `add(id)` and `intervals()` so that `intervals()` returns the seen IDs as a sorted list of disjoint, merged `[start, end]` ranges.
Microsoft
November 29, 20260
0
0 solved
Event IDs arrive one at a time, possibly out of order and with duplicates. Implement `add(id)` and `intervals()` so that `intervals()` returns the seen IDs as a sorted list of disjoint, merged `[start, end]` ranges.
Microsoft onsites use this for teams that ingest telemetry, where a compact summary of received sequence numbers detects gaps. The interviewer wants a sorted structure with binary search and correct merging on both sides.
What the Interviewer Expects
- Store ranges sorted by start and find the insertion point with binary search
- Handle the four cases: inside an existing range, join left, join right, join both
- Ignore duplicates cheaply
- Discuss the cost of list insertion versus a balanced tree
- Explain the trade-off when adds vastly outnumber queries
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if intervals() is called rarely and adds are very frequent?
- How would you also report the gaps (missing IDs) within the observed span?
- How would you shard this across machines when IDs come from many producers?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
add(id): record a non-negative integer, duplicates allowed.intervals(): return sorted disjoint ranges covering exactly the recorded IDs, with adjacent values merged (5 and 6 become[5, 6])....
High-Level Design
Keep two parallel sorted lists, starts and ends, for the current disjoint ranges. For a new value v, i = bisect_right(starts, v) is the first range starting after v, so range i - 1 is the only...