Interval List Intersections solution explained
Interval List Intersections gives you two lists of closed intervals, each sorted and free of overlaps inside its own list, and asks for every stretch the two lists share. Walk both lists with one pointer each: the overlap of the current pair runs from the larger start to the smaller end, and you keep it if that start is not past that end. Then move the pointer whose interval finishes first. That is O(m + n) time for lists of length m and n, with no extra memory beyond the output.
By Evin JohnPublished 8 min read
The problem, restated
Picture two people's busy calendars. Each calendar is a list of blocks [start, end], sorted by start, and no two blocks in the same calendar touch or overlap. Both endpoints belong to the block. Return the list of times when both people are busy at once, as closed intervals in increasing order.
| First list | Second list | Intersections |
|---|---|---|
| [[1, 4], [6, 9], [12, 15]] | [[3, 7], [9, 13]] | [[3, 4], [6, 7], [9, 9], [12, 13]] |
| [[1, 10]] | [[2, 3], [5, 6], [8, 12]] | [[2, 3], [5, 6], [8, 10]] |
| [[5, 5]] | [[5, 8]] | [[5, 5]] |
| [[1, 2]] | [[3, 4]] | [] |
| [[0, 2]] | [] | [] |
The third interval in the first example's output is the one to point at in the interview: [6, 9] and [9, 13] share only the instant 9, and because both ends are included, [9, 9] belongs in the answer.
What the interviewer is checking
This is a short problem, so the bar is a clean loop with no off-by-one slips. Interviewers listen for three things: that you can state the overlap of two intervals as a formula rather than a pile of if statements, that you can justify which pointer to advance, and that you notice the closed endpoints. Some will then ask what changes for three or more lists or for half-open intervals, which shows whether you understood the idea or memorized the code.
Questions worth asking first
- Are the endpoints inclusive? Here they are, which decides whether touching intervals produce a point.
- Is each list already sorted and disjoint? If not, merge and sort each one first, which adds O(m log m + n log n).
- Can a list be empty? Yes. The loop must simply produce nothing.
- Are values integers? The algorithm does not care. It only compares endpoints.
Brute force: every pair
For each interval in the first list and each interval in the second, compute the overlap and keep it if it is not empty. Because both lists are sorted and disjoint, the overlaps found this way come out sorted if you loop over the first list on the outside, so no final sort is needed.
def intersections_slow(first, second):
out = []
for a_lo, a_hi in first:
for b_lo, b_hi in second:
lo, hi = max(a_lo, b_lo), min(a_hi, b_hi)
if lo <= hi:
out.append([lo, hi])
return outWhy are the results already in order? Two overlaps from the same interval of the first list come from different, disjoint intervals of the second list, so they appear in the second list's order. Overlaps from a later interval of the first list lie entirely after the earlier one. Mention this briefly; it shows you think about output order, which many candidates forget.
The overlap formula
Two closed intervals [a, b] and [c, d] share exactly the points from max(a, c) to min(b, d). If that start is greater than that end, they share nothing. This single rule covers every arrangement: one inside the other, partial overlap from either side, touching at a point, and completely separate. Writing it this way removes four or five special cases.
Two pointers: the linear solution
Keep index i into the first list and j into the second. Compute the overlap of first[i] and second[j] and keep it if it is not empty. Then drop whichever of the two intervals ends first. That interval cannot overlap anything later in the other list: every later interval in the other list starts after the current one in that list ends, which is at or after the point where the dropped interval already finished.
def interval_intersection(first, second):
i = j = 0
out = []
while i < len(first) and j < len(second):
lo = max(first[i][0], second[j][0])
hi = min(first[i][1], second[j][1])
if lo <= hi:
out.append([lo, hi])
if first[i][1] < second[j][1]:
i += 1
else:
j += 1
return outfunction intervalIntersection(first, second) {
let i = 0;
let j = 0;
const out = [];
while (i < first.length && j < second.length) {
const lo = Math.max(first[i][0], second[j][0]);
const hi = Math.min(first[i][1], second[j][1]);
if (lo <= hi) out.push([lo, hi]);
if (first[i][1] < second[j][1]) i++;
else j++;
}
return out;
}Trace on the first example
| Pair | max start, min end | Kept | Advance |
|---|---|---|---|
| [1, 4] and [3, 7] | 3, 4 | [3, 4] | first (4 < 7) |
| [6, 9] and [3, 7] | 6, 7 | [6, 7] | second (7 < 9) |
| [6, 9] and [9, 13] | 9, 9 | [9, 9] | first (9 < 13) |
| [12, 15] and [9, 13] | 12, 13 | [12, 13] | second (13 < 15) |
After the last step the second list is used up and the loop stops. Four comparisons for five intervals: each step retires one interval, so the loop runs at most m + n times.
When both intervals end at the same point, it does not matter which pointer moves. Neither interval can overlap anything after the other, because both lists are disjoint, so the next step will drop the other one anyway. The else branch above handles the tie by moving j.
Follow-up: more than two lists
If you need the times when all k people are busy, intersect the first two lists, then intersect the result with the third, and so on. The intermediate result is itself a sorted list of disjoint closed intervals, so the same function applies at every step. The total work is bounded by the sum of all list lengths times k in the worst case, and usually much less because the running result shrinks.
from functools import reduce
def intersect_all(lists):
if not lists:
return []
return reduce(interval_intersection, lists[1:], lists[0])A second answer for k lists is a sweep line: turn every interval into a +1 event at its start and a -1 event just after its end, sort the events, and report the stretches where the running count equals k. With closed integer endpoints, put the end event at end + 1, or order starts before ends at equal times, so that touching intervals still count as overlapping.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Every pair | O(m × n) | O(1) beyond the output |
| Two pointers | O(m + n) | O(1) beyond the output |
| Fold over k lists | O(k × N) worst case | O(N) for the running result |
| Sweep line over k lists | O(N log N) | O(N) for the events |
Edge cases to test
- Either list empty: the loop never runs and the answer is empty.
- A zero-length interval like [5, 5] that sits on another interval's end: the answer contains [5, 5].
- One long interval covering many short ones in the other list: the long one stays while the short ones are dropped one by one.
- Identical lists: the answer equals the input, and every match hits the equal-ends tie.
- Lists that never meet, such as all of one list before all of the other: one pointer runs to the end and nothing is kept.
Common mistakes
- Using lo < hi instead of lo <= hi, which loses single-point overlaps on closed intervals.
- Advancing the interval that starts first instead of the one that ends first. That can skip a later overlap: with [[1, 10]] and [[2, 3], [5, 6]], moving the first list after [2, 3] loses [5, 6].
- Advancing both pointers after every match, which misses the case where one long interval overlaps several short ones.
- Mutating the input intervals to store the overlap, which breaks callers that reuse the lists.
- Writing the overlap test as a chain of cases and getting one arrangement wrong. The max and min formula covers them all.
How to explain it out loud
Fictional example
- Candidate
- Two closed intervals overlap from the larger start to the smaller end, and only if that start is not past that end. So for any pair I can get the overlap in one line.
- Candidate
- Both lists are sorted and disjoint, so I keep one pointer in each. After checking the current pair, whichever interval ends first is finished: everything after it in the other list starts too late to touch it. I move that pointer.
- Interviewer
- What if they end at the same time?
- Candidate
- Then either can go. Neither can overlap the next interval of the other list. Each step drops one interval, so it is linear in the total length, and the output is already in order.
Related problems
Merge Intervals is the natural warm-up: the same max and min reasoning, applied within one list instead of across two. Employee Free Time asks for the opposite question, the gaps when nobody is busy, across many sorted schedules. My Calendar II keeps a running list of pairwise overlaps as bookings arrive, which is this page's formula used inside a design problem.
Practicing with Natively
Short interval problems are a good place to practice talking while you code, because the logic fits in a few lines and the explanation carries the round. In a mock session on Mac or Windows, Natively can transcribe what you say and, once you have tried it yourself, read the problem from a screenshot and suggest an approach to compare against yours. Reading the transcript afterwards tells you whether you mentioned the closed endpoints before the interviewer had to ask. More on the AI interview assistant.
Questions people ask
How do you solve Interval List Intersections?
Keep one pointer per list. The current pair overlaps from max(start1, start2) to min(end1, end2) when that start is not past that end; record it, then advance whichever interval ends first.
Why advance the interval that ends first?
Everything later in the other list starts after the current interval there ends, so an interval that has already finished cannot overlap anything later. Dropping it loses nothing.
What is the time complexity of Interval List Intersections?
O(m + n) time for lists of length m and n, because each step retires one interval, and O(1) extra memory beyond the output.
Do touching intervals count as an intersection?
Yes, when intervals are closed. [6, 9] and [9, 13] share the point 9, so [9, 9] is part of the answer. Use lo <= hi, not lo < hi.
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.
