Data Stream as Disjoint Intervals - Problem

Given a data stream input of non-negative integers a₁, a₂, ..., aₙ, summarize the numbers seen so far as a list of disjoint intervals.

Implement the SummaryRanges class:

  • SummaryRanges() Initializes the object with an empty stream.
  • void addNum(int value) Adds the integer value to the stream.
  • int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [startᵢ, endᵢ].

The answer should be sorted by startᵢ.

Input & Output

Example 1 — Basic Stream Operations
$ Input: operations = ["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "getIntervals"], values = [null, 1, null, 3, null, 2, null, null]
Output: [null, null, [[1,1]], null, [[1,1],[3,3]], null, [[1,3]], [[1,3]]]
💡 Note: Initialize empty stream, add 1 → [[1,1]], add 3 → [[1,1],[3,3]], add 2 → merges to [[1,3]]
Example 2 — Single Interval Growth
$ Input: operations = ["SummaryRanges", "addNum", "addNum", "getIntervals"], values = [null, 1, 2, null]
Output: [null, null, null, [[1,2]]]
💡 Note: Add consecutive numbers 1 and 2, they merge into single interval [1,2]
Example 3 — No Merging Needed
$ Input: operations = ["SummaryRanges", "addNum", "addNum", "getIntervals"], values = [null, 1, 5, null]
Output: [null, null, null, [[1,1],[5,5]]]
💡 Note: Numbers 1 and 5 are not adjacent, so they remain as separate intervals

Constraints

  • 0 ≤ value ≤ 104
  • At most 3 × 104 calls to addNum and getIntervals

Visualization

Tap to expand
Data Stream as Disjoint Intervals132Stream: 1 → 3 → 2Processing Steps:Add 1: [[1,1]]Add 3: [[1,1],[3,3]]Add 2: [[1,3]]Single intervalTwo disjointMerged!Final Result:[[1,3]]
Understanding the Visualization
1
Stream Input
Numbers arrive: 1, 3, 2
2
Interval Building
Track disjoint intervals dynamically
3
Final Intervals
Merged result: [[1,3]]
Key Takeaway
🎯 Key Insight: Maintain sorted disjoint intervals and merge adjacent ones efficiently when new numbers arrive
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
78.4K Views
Medium-High Frequency
~25 min Avg. Time
1.5K 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