Data Stream as Disjoint Intervals (LeetCode 352): Solution and Explanation
Numbers arrive one at a time from a stream of non-negative integers. At any moment you must be able to report everything seen so far as a sorted list of non-overlapping intervals, where consecutive integers are collapsed into a single range.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest design stores every number in a set and, when asked for intervals, sorts the set and walks it, starting a new range whenever two neighbors differ by more than one. That makes addNum O(1) but getIntervals O(u log u) for u distinct values, which is wasteful if the summary is requested often.
The alternative is to keep the summary itself up to date. Because the intervals are disjoint and sorted, a new value can only interact with intervals that touch it, meaning an interval ending at value - 1 or later and starting at value + 1 or earlier. At most two existing intervals can touch it: one on the left that ends right before it and one on the right that starts right after it. Adding the value can therefore extend one interval, bridge two intervals into one, or create a new single point range.
The reference solution handles all three cases with a single linear pass. Intervals that end well before the value are copied as they are, intervals that start well after the value are copied after the new interval is placed, and anything that touches or contains the value is folded into new_interval by taking the minimum start and maximum end. A separate set of seen values lets duplicates return immediately, since a repeated number can never change the summary.
Approach: Sorted interval list with one-pass merge
- Keep
self.intervalsas a sorted list of disjoint[start, end]pairs andself.valuesas a set of numbers already seen. - In
addNum, return immediately ifvalueis already inself.values; otherwise record it. - Start
new_interval = [value, value]and an emptyresult, then scan the existing intervals in order. - If an interval ends before
value - 1, it cannot touch the new value, so copy it toresult. - If an interval starts after
value + 1, placenew_intervalbefore it (once) and then copy the interval. - Otherwise the interval is adjacent to or overlaps the value, so widen
new_intervalto cover it. - After the scan, append
new_intervalif it has not been placed yet, storeresultas the new interval list, and letgetIntervalsreturn it directly.
Step-by-step example
addNum(1), addNum(3), addNum(7), addNum(2), addNum(6)
- After adding 1, 3 and 7, none of them are adjacent, so the list is [[1,1], [3,3], [7,7]].
- addNum(2): [1,1] ends at 1, which is not less than 2 - 1 = 1, so it touches and
new_intervalwidens to [1,2]. - Still in addNum(2): [3,3] starts at 3, which is not greater than 2 + 1 = 3, so it also touches and
new_intervalwidens to [1,3]. - Then [7,7] starts after 3, so [1,3] is placed first and [7,7] follows. The list becomes [[1,3], [7,7]].
- addNum(6): [1,3] ends before 5 and is copied. [7,7] touches 6, so
new_intervalbecomes [6,7]. It is appended at the end, giving [[1,3], [6,7]].
Code: Python, Java, C++
1class SummaryRanges:
2 def __init__(self):
3 self.intervals = []
4 self.values = set()
5
6 def addNum(self, value: int) -> None:
7 if value in self.values:
8 return
9 self.values.add(value)
10
11 intervals = self.intervals
12 new_interval = [value, value]
13
14 # Insert new_interval exactly once, merging any neighbor it touches
15 placed = False
16
17 i = 0
18 result = []
19 while i < len(intervals):
20 interval = intervals[i]
21 if interval[1] < value - 1:
22 result.append(interval)
23 elif interval[0] > value + 1:
24 if not placed:
25 result.append(new_interval)
26 placed = True
27 result.append(interval)
28 else:
29 new_interval[0] = min(new_interval[0], interval[0])
30 new_interval[1] = max(new_interval[1], interval[1])
31 i += 1
32
33 if not placed:
34 result.append(new_interval)
35
36 self.intervals = result
37
38 def getIntervals(self) -> List[List[int]]:
39 return self.intervals1class SummaryRanges {
2 private TreeMap<Integer, int[]> intervals;
3
4 public SummaryRanges() {
5 intervals = new TreeMap<>();
6 }
7
8 public void addNum(int value) {
9 Integer lower = intervals.floorKey(value);
10 Integer higher = intervals.ceilingKey(value);
11
12 if (lower != null && intervals.get(lower)[1] >= value) {
13 return; // Already covered
14 }
15
16 int start = value, end = value;
17
18 if (lower != null && intervals.get(lower)[1] == value - 1) {
19 start = intervals.get(lower)[0];
20 intervals.remove(lower);
21 }
22
23 if (higher != null && higher == value + 1) {
24 end = intervals.get(higher)[1];
25 intervals.remove(higher);
26 }
27
28 intervals.put(start, new int[]{start, end});
29 }
30
31 public int[][] getIntervals() {
32 return intervals.values().toArray(new int[0][]);
33 }
34}1class SummaryRanges {
2 set<pair<int, int>> intervals; // {end, start}
3
4public:
5 SummaryRanges() {}
6
7 void addNum(int value) {
8 auto it = intervals.lower_bound({value, INT_MIN});
9
10 int start = value, end = value;
11
12 if (it != intervals.begin()) {
13 auto prevIt = std::prev(it);
14 if (prevIt->first >= value) return; // Already covered
15 if (prevIt->first == value - 1) {
16 start = prevIt->second;
17 intervals.erase(prevIt);
18 }
19 }
20
21 if (it != intervals.end() && it->second <= value + 1) {
22 end = it->first;
23 intervals.erase(it);
24 }
25
26 intervals.insert({end, start});
27 }
28
29 vector<vector<int>> getIntervals() {
30 vector<vector<int>> result;
31 for (auto& [end, start] : intervals) {
32 result.push_back({start, end});
33 }
34 return result;
35 }
36};Time and space complexity
O(k) per addNum, O(1) per getIntervals
Each insertion scans and rebuilds the list of k current intervals once. Reading the summary just returns the stored list.
O(u)
The set of seen values holds all u distinct numbers, and the interval list never has more than u entries.
Other approaches
Balanced tree or sorted map of interval starts (time O(log k) per addNum, O(k) per getIntervals, space O(k))
Store intervals keyed by start in a TreeMap or SortedList. Use floor and ceiling lookups to find the at most two neighbors of the new value and merge them. This is the better choice when there are many disjoint intervals and frequent inserts.
Set of values, build intervals on demand (time O(1) per addNum, O(u log u) per getIntervals, space O(u))
Insert into a set in constant time and sort plus sweep only when intervals are requested. It is the right trade when reads are rare compared to writes.
Common mistakes
- Only merging overlapping intervals and forgetting adjacent ones, so 2 next to [3,3] produces [[2,2],[3,3]] instead of [[2,3]].
- Missing the bridge case, where a value fills the gap between two intervals and both must collapse into one.
- Inserting the new interval in front of every later interval rather than only the first, which duplicates it when several intervals lie to the right.
- Skipping the duplicate check and then reprocessing a value already inside an interval, which wastes a full scan.
Frequently asked questions
Why can a new number touch at most two intervals?
The intervals are disjoint and separated by gaps of at least one missing integer. A single value can only be adjacent to the interval ending just before it and the one starting just after it, so at most two merges are possible.
What is the follow-up about many merges and few disjoint intervals?
If merges are frequent and the number of disjoint intervals stays small compared to the stream, a linear scan over the intervals is already cheap. A balanced tree still helps when intervals are numerous, because it finds the neighbors in logarithmic time.
Does the set of seen values matter?
It is an optimization. A duplicate value always lies inside an existing interval, so the set lets addNum return in O(1) instead of scanning and rebuilding the list for no change.