Skip to content

Data Stream as Disjoint Intervals

HardIntervals
Decode it first. Clues, constraints, pattern and plan before any code.

Build a SummaryRanges class that receives non-negative integers one at a time and can summarise everything seen so far as a sorted list of disjoint intervals.

  • add_num(value) adds value to the stream (addNum in TypeScript).
  • get_intervals() returns the current summary as [[start, end], ...], sorted by start (getIntervals in TypeScript).

Consecutive numbers join into one interval, and repeated values change nothing.

add_num(1)  →  [[1, 1]]
add_num(3)  →  [[1, 1], [3, 3]]
add_num(7)  →  [[1, 1], [3, 3], [7, 7]]
add_num(2)  →  [[1, 3], [7, 7]]
add_num(6)  →  [[1, 3], [6, 7]]

Constraints

  • 0 <= value <= 10^4
  • At most 3 * 10^4 calls in total.
  • Follow-up: there are many additions and the number of intervals stays small.