SDE & MLE Prep

352. Data Stream as Disjoint Intervals

Problem

Design SummaryRanges for a stream of non-negative integers: addNum(value) adds a number and getIntervals() returns the numbers seen so far as a sorted list of disjoint intervals [start, end].

Example: add 1, 3, 7, 2, 6 → getIntervals() = [[1,3],[6,7]]

Constraints: follow-up: many merges and few distinct intervals compared with the stream length.

Store disjoint intervals keyed by start in a sorted structure. On addNum(v): find the interval ending at or after v−1 from the left and the one starting at v+1; merge with either, both, or create [v, v].

Complexity: O(log n) per add with a balanced tree; getIntervals O(n).

class SummaryRanges:
    def __init__(self):
        self.iv = []                                   # sorted, disjoint [start, end]

    def addNum(self, value: int) -> None:
        iv = self.iv
        i = bisect.bisect_left(iv, [value + 1])        # first interval starting > value
        if i > 0 and iv[i - 1][1] >= value:            # already covered
            return
        left = i > 0 and iv[i - 1][1] == value - 1
        right = i < len(iv) and iv[i][0] == value + 1
        if left and right:
            iv[i - 1][1] = iv[i][1]
            iv.pop(i)
        elif left:
            iv[i - 1][1] = value
        elif right:
            iv[i][0] = value
        else:
            iv.insert(i, [value, value])

    def getIntervals(self) -> List[List[int]]:
        return [x[:] for x in self.iv]