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 Intervals INPUT Data Stream Operations SummaryRanges() addNum(1) getIntervals() --> [[1,1]] addNum(3) getIntervals() --> [[1,1],[3,3]] addNum(2) getIntervals() --> [[1,3]] Number Line 1 2 3 Values: 1, 3, 2 (in order) ALGORITHM STEPS 1 Binary Search Find insert position in sorted interval list 2 Check Neighbors Can merge with prev/next intervals? 3 Merge Intervals Combine adjacent if val connects them 4 Return Intervals Return sorted disjoint interval list Merge Example: [1,1] [3,3] + add(2) --> [1, 3] FINAL RESULT Step-by-step Results: After add(1): [1,1] After add(3): [1,1] [3,3] After add(2): MERGED! [1, 3] Final Output: [[1, 3]] 1 merged interval OK - Correct! All intervals disjoint and sorted Key Insight: Using a sorted list with binary search (O(log n)) allows efficient insertion and merging. When adding a number, check if it can extend or merge adjacent intervals: if prev.end + 1 == val and val + 1 == next.start, merge all three into one interval. TutorialsPoint - Data Stream as Disjoint Intervals | Sorted List with Binary Search Time: O(n) per add | Space: O(n) for intervals
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