Data Stream as Disjoint Intervals solution explained
Data Stream as Disjoint Intervals asks for a class that receives non-negative integers one at a time and, when asked, returns everything seen so far as sorted runs of consecutive numbers, such as [[1, 3], [6, 6]]. Keep the runs as a sorted list of [start, end] pairs. For each new value, binary search for the run that starts at or before it; the value is either already covered, extends that run, extends the next run, bridges the two into one, or starts a new run. Search is O(log k) for k runs, and getIntervals just returns the list.
By Evin JohnPublished 8 min read
The problem, restated
Design a class with two methods. addNum(value) receives a non-negative integer; values may repeat and arrive in any order. getIntervals() returns the set of values seen so far, written as a sorted list of disjoint closed intervals where each interval covers a run of consecutive integers. Two runs that become adjacent, like [3, 4] and [5, 5], must be reported as one run [3, 5].
| addNum | getIntervals() | Case |
|---|---|---|
| 7 | [[7, 7]] | New run |
| 3 | [[3, 3], [7, 7]] | New run |
| 5 | [[3, 3], [5, 5], [7, 7]] | New run, nothing adjacent |
| 4 | [[3, 5], [7, 7]] | Bridges [3, 3] and [5, 5] |
| 6 | [[3, 7]] | Bridges [3, 5] and [7, 7] |
| 6 | [[3, 7]] | Already covered |
| 8 | [[3, 8]] | Extends the run on its left |
| 2 | [[2, 8]] | Extends the run on its right |
| 0 | [[0, 0], [2, 8]] | New run; 1 is still missing |
What the interviewer is checking
This is a data structure design question disguised as an interval problem. The interviewer wants a clean case analysis for one insertion, a choice of structure that makes the neighbor lookup fast, and a conversation about which operation should be cheap. A strong candidate asks how often getIntervals is called compared with addNum, because that decides between keeping runs merged at all times and building them lazily.
Follow-ups you may hear
- Lots of merges, and the number of runs stays small compared with the stream. Keeping merged runs is the right call: memory is O(k) runs, not O(m) values.
- Reads are rare. Store values in a set and sort when asked.
- Values can also be removed. A removal can split a run in two; the sorted-run structure handles it with the same neighbor lookup.
- Strict O(log k) per add. Use a balanced tree map keyed by run start.
Lazy version: a set, sorted on demand
The easiest correct answer stores every distinct value in a set. getIntervals sorts the set and sweeps it, starting a new run whenever a value is not one more than the previous one. Adds are O(1) on average and reads are O(m log m) for m distinct values. It is a fine first answer and a good test oracle.
class SummaryRangesLazy:
def __init__(self):
self.seen = set()
def addNum(self, value):
self.seen.add(value)
def getIntervals(self):
runs = []
for v in sorted(self.seen):
if runs and v == runs[-1][1] + 1:
runs[-1][1] = v
else:
runs.append([v, v])
return runsEager version: sorted runs and binary search
Keep the runs sorted by start in two parallel lists, starts and ends. For a new value, find i, the index of the last run whose start is at most the value, with a binary search. Only run i and run i + 1 can be affected. Then check the cases in this order:
- CoveredIf run i exists and value <= ends[i], the value is already summarized. Do nothing.
- Touches bothIf run i ends at value - 1 and run i + 1 starts at value + 1, the value bridges them: set ends[i] to ends[i + 1] and delete run i + 1.
- Touches the left runIf run i ends at value - 1, set ends[i] = value.
- Touches the right runIf run i + 1 starts at value + 1, set starts[i + 1] = value.
- AloneOtherwise insert the new run [value, value] at position i + 1.
from bisect import bisect_right
class SummaryRanges:
def __init__(self):
self.starts = []
self.ends = []
def addNum(self, value):
i = bisect_right(self.starts, value) - 1
if i >= 0 and value <= self.ends[i]:
return
joins_left = i >= 0 and self.ends[i] == value - 1
nxt = i + 1
joins_right = nxt < len(self.starts) and self.starts[nxt] == value + 1
if joins_left and joins_right:
self.ends[i] = self.ends[nxt]
del self.starts[nxt]
del self.ends[nxt]
elif joins_left:
self.ends[i] = value
elif joins_right:
self.starts[nxt] = value
else:
self.starts.insert(nxt, value)
self.ends.insert(nxt, value)
def getIntervals(self):
return [[s, e] for s, e in zip(self.starts, self.ends)]class SummaryRanges {
constructor() {
this.runs = [];
}
lastStartAtMost(value) {
let lo = 0;
let hi = this.runs.length - 1;
let found = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (this.runs[mid][0] <= value) {
found = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return found;
}
addNum(value) {
const runs = this.runs;
const i = this.lastStartAtMost(value);
if (i >= 0 && value <= runs[i][1]) return;
const joinsLeft = i >= 0 && runs[i][1] === value - 1;
const joinsRight = i + 1 < runs.length && runs[i + 1][0] === value + 1;
if (joinsLeft && joinsRight) {
runs[i][1] = runs[i + 1][1];
runs.splice(i + 1, 1);
} else if (joinsLeft) {
runs[i][1] = value;
} else if (joinsRight) {
runs[i + 1][0] = value;
} else {
runs.splice(i + 1, 0, [value, value]);
}
}
getIntervals() {
return this.runs.map((r) => [r[0], r[1]]);
}
}getIntervals returns copies. If it handed back the internal arrays, a caller who edits the result would corrupt the structure, and in JavaScript that kind of shared reference is easy to create by accident.
Why only two runs can be affected
Runs are disjoint and not adjacent, so between run i and run i + 1 there is a gap of at least one missing number. A new value can change only the runs whose ends sit within one of it. Run i is the last one starting at or before the value, so any earlier run ends at least two below it, and any run after i + 1 starts at least two above it. That is why the case analysis never looks further than one run in each direction.
Complexity
| Approach | addNum | getIntervals | Memory |
|---|---|---|---|
| Set, sorted on read | O(1) average | O(m log m) | O(m) |
| Sorted runs in arrays | O(log k) search, O(k) worst case insert or delete | O(k) | O(k) |
| Balanced tree map of runs | O(log k) | O(k) | O(k) |
When most values merge into a few long runs, the eager structure is small and fast. When values are scattered and getIntervals is called after every add, both versions do similar work, and the eager one wins because each read is O(k) instead of a fresh sort.
Edge cases
- Duplicate values, including a value that equals a run's start or end.
- The value 0, where value - 1 is negative and no run can end there.
- A value that bridges two runs, which must delete one run, not leave two overlapping entries.
- A value that lands one below the first run, where i is -1.
- getIntervals before any add returns an empty list.
Common mistakes
- Checking the left neighbor and the right neighbor separately and applying both updates, which leaves two runs that should have become one.
- Searching for the first start greater than the value and forgetting to step back one, so the covering run is missed.
- Treating a duplicate inside a run as a new run.
- Returning internal arrays from getIntervals.
- Sorting the whole run list after every insertion instead of inserting at the found position.
How to explain it out loud
Fictional example
- Candidate
- Before I pick a structure: how often is getIntervals called compared with addNum? If reads are rare, I would store a set and build the runs on demand.
- Interviewer
- Assume reads are frequent.
- Candidate
- Then I keep the runs merged. Runs are sorted and never adjacent, so a new value can only touch the run that starts at or before it and the next one. I binary search for the first, then check: covered, bridges both, extends left, extends right, or new run.
- Candidate
- The search is log k. Inserting into an array can shift up to k runs; with a tree map that becomes log k too.
Related problems
Range Module maintains the same merged structure for whole ranges and also supports removal. Count of Range Sum is a counting problem, but it leans on the same skill of keeping data sorted while it changes. Process Tasks Using Servers is another simulation where the right structure for the next lookup decides the complexity.
Practicing with Natively
The question about read and write frequency is the moment that makes this answer stand out, and it is easy to forget under pressure. Run a mock on Mac or Windows with Natively transcribing, then check the transcript for whether you asked it. After your own attempt, Natively can also read the problem from a screenshot and suggest an approach to set beside yours. See the AI interview assistant for details.
Questions people ask
How do you solve Data Stream as Disjoint Intervals?
Keep sorted runs. For each value, binary search for the last run starting at or before it; then the value is covered, extends that run, extends the next run, bridges both, or starts a new run.
Why only check two runs when adding a number?
Runs are disjoint and never adjacent, so every other run is at least two away from the new value. Only the run starting at or before it and the next run can change.
What is the time complexity?
O(log k) to find the neighbors among k runs, plus O(k) worst case to insert or delete in an array, and O(k) to return the intervals. A lazy set makes adds O(1) and reads O(m log m).
When is the lazy set approach better?
When getIntervals is called rarely compared with addNum. Then sorting the seen values on demand is cheaper than keeping runs merged on every add.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
