First fix the conventions out loud: an interval is [start, end], are the ends included, and do two intervals that only touch ([1, 3] and [3, 5]) count as overlapping? Two intervals overlap exactly when a.start <= b.end && b.start <= a.end. Merge is sort by start, then sweep: if the next interval starts at or before the end of the last merged one, extend that end to the larger of the two; otherwise start a new one. That's O(n log n) for the sort. For the class, the design choice is when to pay: store raw intervals and merge on demand, or keep the list sorted and merged at all times, so insert is a binary search plus a splice and an overlap query is O(log n). The second is what an interviewer is usually steering toward.
Intervals problem: design a class with related methods (insert, overlap, merge) over a list of intervals.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
insert validates and appends. overlapping is the one-line overlap test applied to every stored interval. merge copies and sorts by start, then sweeps once: because of the sort, an interval can only overlap the most recent merged one, so comparing with last is enough, and Math.max handles an interval that sits inside the previous one. The last check shows the cost: 100 identical inserts are all kept, and every query reads all of them.
// Intervals are [start, end] with both ends included, so [1, 3] and [3, 5] touch and merge.// The simple design: store what is inserted; do the work when asked.class Intervals {constructor(list = []) {this.list = [];for (const [start, end] of list) this.insert(start, end);}insert(start, end) {if (!(start <= end)) throw new RangeError('start must not be after end');this.list.push([start, end]);}// Every stored interval that shares at least one point with [start, end].overlapping(start, end) {return this.list.filter(([s, e]) => s <= end && start <= e).map(([s, e]) => [s, e]);}// Sorted, with overlapping and touching intervals joined.merge() {const sorted = [...this.list].sort((a, b) => a[0] - b[0]);const out = [];for (const [s, e] of sorted) {const last = out[out.length - 1];if (last && s <= last[1]) last[1] = Math.max(last[1], e);else out.push([s, e]);}return out;}}
passes 8 checks run on every build, against the native method where there is one
- merge joins overlapping intervals and sorts them
- touching intervals merge; a gap keeps them apart
- an interval inside another disappears into it
- insert adds to the set; one insert can join several
- overlapping returns the intervals a range meets, ends included
- a single point is a valid interval; a backwards one is an error
- empty, and results are copies
- the weakness: everything inserted is kept, and every query scans it all
The list holds disjoint intervals in order, so their ends are sorted too. firstEndingFrom(start) binary-searches for the first interval that could reach the new one; from there insert swallows every interval that begins at or before the new end, widening as it goes, and replaces them all with one splice. Queries use the same search, so overlaps reads about log n intervals. The random check compares 200 inserts against the sort-and-sweep answer.
// Keep the list sorted and already merged. Then insert only touches the intervals it overlaps,// and a query is a binary search instead of a scan.class Intervals {constructor(list = []) {this.list = []; // sorted by start; no two overlap or touchfor (const [start, end] of list) this.insert(start, end);}// Index of the first interval that ends at or after `point` (binary search).firstEndingFrom(point) {let lo = 0;let hi = this.list.length;while (lo < hi) {const mid = (lo + hi) >> 1;if (this.list[mid][1] < point) lo = mid + 1;else hi = mid;}return lo;}insert(start, end) {if (!(start <= end)) throw new RangeError('start must not be after end');const from = this.firstEndingFrom(start);let to = from;// Swallow every interval the new one reaches.while (to < this.list.length && this.list[to][0] <= end) {start = Math.min(start, this.list[to][0]);end = Math.max(end, this.list[to][1]);to++;}this.list.splice(from, to - from, [start, end]);}overlapping(start, end) {const out = [];for (let i = this.firstEndingFrom(start); i < this.list.length && this.list[i][0] <= end; i++) {out.push([...this.list[i]]);}return out;}overlaps(start, end) {const i = this.firstEndingFrom(start);return i < this.list.length && this.list[i][0] <= end;}merge() {return this.list.map(([s, e]) => [s, e]); // already merged; a copy, so callers can't break the order}}
passes 11 checks run on every build, against the native method where there is one
- merge joins overlapping intervals and sorts them
- touching intervals merge; a gap keeps them apart
- an interval inside another disappears into it
- insert adds to the set; one insert can join several
- overlapping returns the intervals a range meets, ends included
- a single point is a valid interval; a backwards one is an error
- empty, and results are copies
- the list stays merged after every insert
- overlaps answers yes or no
- a query looks at about log n intervals, not all of them
- random inserts match the sort-and-sweep answer
With the invariant in place, the useful questions are short. covers needs a single interval that contains the whole range, since merged intervals never touch. gaps walks the intervals inside a range with a cursor and reports each stretch the cursor has to jump: a calendar's free slots. total is a plain sum, because nothing overlaps.
// The sorted, merged list makes the questions people really ask cheap: is this slot covered,// where are the gaps, how much is booked in total.class Intervals {constructor(list = []) {this.list = []; // sorted by start; no two overlap or touchfor (const [start, end] of list) this.insert(start, end);}// Index of the first interval that ends at or after `point` (binary search).firstEndingFrom(point) {let lo = 0;let hi = this.list.length;while (lo < hi) {const mid = (lo + hi) >> 1;if (this.list[mid][1] < point) lo = mid + 1;else hi = mid;}return lo;}insert(start, end) {if (!(start <= end)) throw new RangeError('start must not be after end');const from = this.firstEndingFrom(start);let to = from;// Swallow every interval the new one reaches.while (to < this.list.length && this.list[to][0] <= end) {start = Math.min(start, this.list[to][0]);end = Math.max(end, this.list[to][1]);to++;}this.list.splice(from, to - from, [start, end]);}overlapping(start, end) {const out = [];for (let i = this.firstEndingFrom(start); i < this.list.length && this.list[i][0] <= end; i++) {out.push([...this.list[i]]);}return out;}overlaps(start, end) {const i = this.firstEndingFrom(start);return i < this.list.length && this.list[i][0] <= end;}merge() {return this.list.map(([s, e]) => [s, e]);}// Is every point of [start, end] inside one stored interval?covers(start, end) {const i = this.firstEndingFrom(start);return i < this.list.length && this.list[i][0] <= start && end <= this.list[i][1];}// The free stretches inside [start, end]: what a calendar calls open slots.gaps(start, end) {const out = [];let cursor = start;for (let i = this.firstEndingFrom(start); i < this.list.length && this.list[i][0] <= end; i++) {const [s, e] = this.list[i];if (s > cursor) out.push([cursor, s]);cursor = e;}if (cursor < end) out.push([cursor, end]);return out;}// Total length covered. Overlaps were merged on insert, so nothing is counted twice.total() {return this.list.reduce((sum, [s, e]) => sum + (e - s), 0);}}
passes 14 checks run on every build, against the native method where there is one
- merge joins overlapping intervals and sorts them
- touching intervals merge; a gap keeps them apart
- an interval inside another disappears into it
- insert adds to the set; one insert can join several
- overlapping returns the intervals a range meets, ends included
- a single point is a valid interval; a backwards one is an error
- empty, and results are copies
- the list stays merged after every insert
- overlaps answers yes or no
- a query looks at about log n intervals, not all of them
- random inserts match the sort-and-sweep answer
- covers: the whole range must sit inside one interval
- gaps: the free stretches inside a range
- total: overlapping bookings aren't counted twice
Calendars and booking
Busy times are intervals: merging gives the day's busy blocks, the gaps are the free slots to offer, and an overlap query is the double-booking check.
Buffered ranges in media
A video element reports what it has downloaded as a TimeRanges list: sorted, non-overlapping time intervals, the invariant of the intermediate stage.
Interval trees
When intervals must be kept separate (not merged) and queried often, an interval tree answers "what overlaps this range" in O(log n + k).
Merging without sorting first.
Setting the merged end to the new interval's end instead of the larger of the two, which shrinks
[1, 10]when[3, 4]arrives.Getting the overlap test wrong for nested intervals;
a.start <= b.end && b.start <= a.endcovers every case.Not deciding whether touching intervals merge, or whether ends are included.
The default
sort()on numbers, which compares them as strings.Handing out the internal arrays, so a caller can break the sorted order.
What's the cost of each method?
Basic: insert O(1), overlap query O(n), merge O(n log n). Sorted and merged: the search is O(log n), insert is O(n) in the worst case because splice shifts the array, queries are O(log n + k) for k results.
How would you remove a range?
Find the intervals it overlaps the same way, then replace them with what's left on either side: up to two pieces. With included integer ends the pieces end at start - 1 and begin at end + 1; with half-open intervals they share the cut points, which is one reason [start, end) is the easier convention.
What if intervals carry data and must not be merged?
Then merging loses information. Keep them separate in an interval tree, or in a list sorted by start with the largest end so far stored alongside, to answer overlap queries quickly.
How do you find the maximum number overlapping at once?
Sweep line: turn each interval into a +1 at its start and a -1 at its end, sort the events, and track the running sum.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
- developer.mozilla.org/en-US/docs/Web/API/TimeRanges
- en.wikipedia.org/wiki/Interval_scheduling
- en.wikipedia.org/wiki/Interval_tree
- en.wikipedia.org/wiki/Binary_search