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]
sr = SummaryRanges()
out = []
for v in (1, 3, 7, 2, 6):
sr.addNum(v)
out.append(sr.getIntervals())
assert out == [[[1, 1]], [[1, 1], [3, 3]], [[1, 1], [3, 3], [7, 7]], [[1, 3], [7, 7]], [[1, 3], [6, 7]]]
class SummaryRanges {
private final TreeMap<Integer, Integer> iv = new TreeMap<>(); // start -> end
public void addNum(int value) {
Integer lo = iv.floorKey(value), hi = iv.ceilingKey(value + 1);
if (lo != null && iv.get(lo) >= value) return;
boolean left = lo != null && iv.get(lo) == value - 1, right = hi != null && hi == value + 1;
if (left && right) { iv.put(lo, iv.get(hi)); iv.remove(hi); }
else if (left) iv.put(lo, value);
else if (right) { iv.put(value, iv.get(hi)); iv.remove(hi); }
else iv.put(value, value);
}
public int[][] getIntervals() {
int[][] res = new int[iv.size()][];
int i = 0;
for (Map.Entry<Integer, Integer> e : iv.entrySet()) res[i++] = new int[]{e.getKey(), e.getValue()};
return res;
}
}
type SummaryRanges struct {
iv [][]int // sorted, disjoint [start, end]
}
func Constructor() SummaryRanges {
return SummaryRanges{}
}
func (this *SummaryRanges) AddNum(value int) {
iv := this.iv
i := sort.Search(len(iv), func(k int) bool { return iv[k][0] > value }) // first interval starting after value
if i > 0 && iv[i-1][1] >= value {
return // already covered
}
left := i > 0 && iv[i-1][1] == value-1
right := i < len(iv) && iv[i][0] == value+1
switch {
case left && right: // value bridges two intervals
iv[i-1][1] = iv[i][1]
this.iv = append(iv[:i], iv[i+1:]...)
case left:
iv[i-1][1] = value
case right:
iv[i][0] = value
default:
iv = append(iv, []int{value, value})
copy(iv[i+1:], iv[i:])
iv[i] = []int{value, value}
this.iv = iv
}
}
func (this *SummaryRanges) GetIntervals() [][]int {
out := make([][]int, len(this.iv))
for i, x := range this.iv {
out[i] = []int{x[0], x[1]}
}
return out
}