Data Stream As Disjoint Intervals Problem
Description
LeetCode Problem 352.
Given a data stream input of non-negative integers a_1, a_2, ..., a_n, 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 val) Adds the integer val to the stream.
- int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [start_i, end_i].
Example 1:
Input
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
Output
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]
Explanation
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // return [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]
Constraints:
- 0 <= val <= 10^4
- At most 3 * 10^4 calls will be made to addNum and getIntervals.
Solution
Approach: Sorted Intervals with Binary Search
Keep the answer itself up to date: a list of disjoint intervals [start, end], sorted by start, with no two intervals touching (there is always a gap of at least one missing number between them). Then getIntervals only has to copy the list.
To add a number value:
- Binary search for
i, the number of intervals whosestartis at mostvalue. The interval just before positioniis the only one that can already containvalueor end right before it; the interval atiis the only one that can start right after it. - If interval
i - 1already reachesvalue(end >= value), do nothing: the stream may repeat numbers. - Otherwise check the two neighbors:
valuetouches both (endof the left isvalue - 1andstartof the right isvalue + 1): it fills the gap, so merge the two into one interval.- It touches only the left one: extend its
endtovalue. - It touches only the right one: move its
starttovalue. - It touches neither: insert
[value, value]at positioni.
The case people miss is the merge: adding 2 to [[1, 1], [3, 3]] must give [[1, 3]], not [[1, 2], [3, 3]].
Complexity: addNum takes O(log k) time to search plus O(k) in the worst case to insert or remove in the list, where k is the current number of intervals (at most 5001 here, since val is at most 104). getIntervals takes O(k) time to copy. O(k) space.
class SummaryRanges:
def __init__(self):
self.intervals = [] # disjoint [start, end] pairs, sorted by start
def addNum(self, value: int) -> None:
intervals = self.intervals
# i = number of intervals that start at or before value
lo, hi = 0, len(intervals)
while lo < hi:
mid = (lo + hi) // 2
if intervals[mid][0] <= value:
lo = mid + 1
else:
hi = mid
i = lo
if i > 0 and intervals[i - 1][1] >= value:
return # value is already covered
joins_left = i > 0 and intervals[i - 1][1] == value - 1
joins_right = i < len(intervals) and intervals[i][0] == value + 1
if joins_left and joins_right:
# value fills the gap between two intervals: merge them
intervals[i - 1][1] = intervals[i][1]
intervals.pop(i)
elif joins_left:
intervals[i - 1][1] = value
elif joins_right:
intervals[i][0] = value
else:
intervals.insert(i, [value, value])
def getIntervals(self) -> List[List[int]]:
return [[start, end] for start, end in self.intervals]
Now write it from memory
Close the write-up and solve it yourself against the tests.