Skip to content
Decoder

Data Stream as Disjoint Intervals

Hard

Problem

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.

Example 1

Input
add_num(1)
Output
[[1, 1]]

Example 2

Input
add_num(3)
Output
[[1, 1], [3, 3]]

Example 3

Input
add_num(7)
Output
[[1, 1], [3, 3], [7, 7]]

Example 4

Input
add_num(2)
Output
[[1, 3], [7, 7]]

Example 5

Input
add_num(6)
Output
[[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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.