Data Stream as Disjoint Intervals - Problem

๐ŸŒŠ Data Stream as Disjoint Intervals

Imagine you're receiving a continuous stream of numbers and need to efficiently track which ranges of consecutive numbers you've seen. This is a classic data structure design problem that tests your ability to maintain sorted, disjoint intervals dynamically.

The Challenge: As numbers arrive one by one, you must:

  • Add each new number to your collection
  • Merge overlapping or adjacent intervals
  • Return all intervals sorted by their start points

Example: If you receive numbers [1, 3, 7, 2, 6], your intervals evolve like this:

  • After 1: [[1,1]]
  • After 3: [[1,1], [3,3]]
  • After 7: [[1,1], [3,3], [7,7]]
  • After 2: [[1,3], [7,7]] (merged!)
  • After 6: [[1,3], [6,7]]

You need to implement the SummaryRanges class with efficient addNum() and getIntervals() methods.

Input & Output

example_1.py โ€” Basic Operations
$ Input: ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [], [3], [], [2], []]
โ€บ Output: [null, null, [[1,1]], null, [[1,1],[3,3]], null, [[1,3]]]
๐Ÿ’ก Note: Start empty, add 1 โ†’ [1,1], add 3 โ†’ [1,1],[3,3], add 2 โ†’ merges into [1,3] since 2 connects 1 and 3
example_2.py โ€” Multiple Merges
$ Input: ["SummaryRanges", "addNum", "addNum", "addNum", "getIntervals", "addNum", "getIntervals"] [[], [1], [7], [3], [], [2], []]
โ€บ Output: [null, null, null, null, [[1,1],[3,3],[7,7]], null, [[1,3],[7,7]]]
๐Ÿ’ก Note: Add 1,7,3 creates three separate intervals. Adding 2 merges [1,1] and [3,3] into [1,3]
example_3.py โ€” Adjacent Intervals
$ Input: ["SummaryRanges", "addNum", "addNum", "addNum", "getIntervals"] [[], [1], [2], [4], []]
โ€บ Output: [null, null, null, null, [[1,2],[4,4]]]
๐Ÿ’ก Note: 1 and 2 are consecutive so they merge into [1,2]. 4 is separate, creating [1,2],[4,4]

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log n) per addNum, O(n) per getIntervals

Tree operations are O(log n), getIntervals needs to collect all intervals

n
2n
โšก Linearithmic
Space Complexity
O(n)

TreeMap nodes plus interval storage

n
2n
โšก Linearithmic Space

Constraints

  • 0 โ‰ค value โ‰ค 104
  • At most 3 ร— 104 calls will be made to addNum and getIntervals
  • All values are non-negative integers
  • getIntervals should return intervals sorted by start position
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen