sagelearnai

Data Stream as Disjoint Intervals

Difficulty: Hard · Pattern: Intervals · LeetCode #352

Numbers arrive in a stream. Implement:

  • addNum(value): add a non-negative integer.
  • getIntervals(): return the numbers seen so far as a sorted list of disjoint intervals [start, end] that merge consecutive values.

Example

text
addNum(1); getIntervals() → [[1,1]]
addNum(3); getIntervals() → [[1,1],[3,3]]
addNum(7); getIntervals() → [[1,1],[3,3],[7,7]]
addNum(2); getIntervals() → [[1,3],[7,7]]
addNum(6); getIntervals() → [[1,3],[6,7]]

Hints

  1. Keep a sorted list of disjoint intervals. A new value can extend the interval on its left, the one on its right, both (bridging them) or neither.
  2. Binary-search for the last interval with start ≤ value.

Approach

Keep iv, a list of intervals sorted by start. For addNum(v):

  1. i = the index of the last interval with start ≤ v (bisect).
  2. If that interval already contains v, do nothing.
  3. joinLeft = (i ≥ 0 and iv[i].end + 1 == v), joinRight = (i+1 < len and iv[i+1].start == v + 1).
  4. Both: merge iv[i] and iv[i+1]. Left only: extend iv[i].end. Right only: extend iv[i+1].start. Neither: insert [v,v] at i+1.

getIntervals returns the list. Use a balanced BST / TreeMap for O(log n) inserts. In Python, a list insert is O(n), but that's fine for the follow-up of "few intervals, many numbers".

Complexity

Time: O(log k) search + O(k) list insert, where k = number of intervals. Space: O(k).

Python solution
import bisect

class SummaryRanges:
    def __init__(self):
        self.iv = []

    def addNum(self, value):
        iv = self.iv
        i = bisect.bisect_right(iv, [value, float('inf')]) - 1
        if i >= 0 and iv[i][0] <= value <= iv[i][1]:
            return
        left = i >= 0 and iv[i][1] + 1 == value
        right = i + 1 < len(iv) and iv[i + 1][0] == value + 1
        if left and right:
            iv[i][1] = iv[i + 1][1]
            iv.pop(i + 1)
        elif left:
            iv[i][1] = value
        elif right:
            iv[i + 1][0] = value
        else:
            iv.insert(i + 1, [value, value])

    def getIntervals(self):
        return [x[:] for x in self.iv]
JavaScript solution
class SummaryRanges {
  constructor() { this.iv = []; }
  addNum(v) {
    const iv = this.iv;
    let lo = 0, hi = iv.length;
    while (lo < hi) { const m = (lo + hi) >> 1; if (iv[m][0] <= v) lo = m + 1; else hi = m; }
    const i = lo - 1;
    if (i >= 0 && iv[i][1] >= v) return;
    const left = i >= 0 && iv[i][1] + 1 === v, right = i + 1 < iv.length && iv[i + 1][0] === v + 1;
    if (left && right) { iv[i][1] = iv[i + 1][1]; iv.splice(i + 1, 1); }
    else if (left) iv[i][1] = v;
    else if (right) iv[i + 1][0] = v;
    else iv.splice(i + 1, 0, [v, v]);
  }
  getIntervals() { return this.iv.map((x) => [...x]); }
}