Data Stream as Disjoint Intervals (LeetCode 352): Solution and Explanation

Hard
Binary Search
Design
Ordered Set

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Keep self.intervals as a sorted list of disjoint [start, end] pairs and self.values as a set of numbers already seen.
  2. In addNum, return immediately if value is already in self.values; otherwise record it.
  3. Start new_interval = [value, value] and an empty result, then scan the existing intervals in order.
  4. If an interval ends before value - 1, it cannot touch the new value, so copy it to result.
  5. If an interval starts after value + 1, place new_interval before it (once) and then copy the interval.
  6. Otherwise the interval is adjacent to or overlaps the value, so widen new_interval to cover it.
  7. After the scan, append new_interval if it has not been placed yet, store result as the new interval list, and let getIntervals return it directly.

Step-by-step example

addNum(1), addNum(3), addNum(7), addNum(2), addNum(6)
  1. After adding 1, 3 and 7, none of them are adjacent, so the list is [[1,1], [3,3], [7,7]].
  2. addNum(2): [1,1] ends at 1, which is not less than 2 - 1 = 1, so it touches and new_interval widens to [1,2].
  3. Still in addNum(2): [3,3] starts at 3, which is not greater than 2 + 1 = 3, so it also touches and new_interval widens to [1,3].
  4. Then [7,7] starts after 3, so [1,3] is placed first and [7,7] follows. The list becomes [[1,3], [7,7]].
  5. addNum(6): [1,3] ends before 5 and is copied. [7,7] touches 6, so new_interval becomes [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.intervals

Time and space complexity

Time

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.

Space

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.