Data Stream as Disjoint Intervals

Hard · Intervals · Binary Search · Design · Ordered Set

Problem

Non-negative integers arrive one at a time. At any moment you must be able to summarize everything seen so far as a sorted list of disjoint intervals, where runs of consecutive integers are merged: seeing 1, 3, 7, 2, 6 gives [1,3] and [6,7].

Implement SummaryRanges:

Tests replay a call sequence: the first entry names the class and its constructor arguments, each later entry is a method with its arguments, and calls returning nothing report None.

Examples

Input: ops = ["SummaryRanges","addNum","getIntervals","addNum","getIntervals","addNum","getIntervals","addNum","getIntervals"], args = [[],[1],[],[3],[],[7],[],[2],[]]
Output: [None, None, [[1, 1]], None, [[1, 1], [3, 3]], None, [[1, 1], [3, 3], [7, 7]], None, [[1, 3], [7, 7]]]

Adding 2 fills the gap between [1,1] and [3,3], so they merge into [1,3].

Input: ops = ["SummaryRanges","addNum","addNum","addNum","getIntervals"], args = [[],[2],[2],[9],[]]
Output: [None, None, None, None, [[2, 2], [9, 9]]]

The second 2 is already covered.

Input: ops = ["SummaryRanges","getIntervals","addNum","getIntervals"], args = [[],[],[0],[]]
Output: [None, [], None, [[0, 0]]]

An empty stream has no intervals; 0 is a valid value.

Constraints

Approaches

Follow-up

With many more getIntervals calls than additions, keep the intervals as above. If additions dominate and the interval list is rarely read, storing raw values and merging on demand is cheaper per add. The use cases ask, after each addition, how many intervals there are and how long the longest one is.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…