Data Stream as Disjoint Intervals
Design a SummaryRanges data structure that ingests a stream of non-negative integers one at a time. addNum(value) records a seen integer, and getIntervals() returns the current set of seen numbers compressed into a sorted list of disjoint inclusive intervals [start, end].
Open official problem prompt ↗Keep a growing set of integers compressed at all times into the minimum number of disjoint sorted intervals, and answer that compressed view on demand.
Think of booking seats in a row one by one. Each new seat either extends a block of already-taken seats, joins two blocks into one, or begins a new block. You never rescan the whole row; you just look at the seats immediately beside the one you took.
- Input
- addNum(1), addNum(3), addNum(7), addNum(2), addNum(6), then getIntervals()
- Output
- [[1, 3], [6, 7]]
- Why
- Seen numbers are {1,2,3,6,7}; consecutive runs 1..3 and 6..7 collapse into two intervals.
0 <= value <= 10^4At most 3 * 10^4 calls to addNum and getIntervalsgetIntervals may be called frequently, so keep it cheap