The intervals pattern, with templates
Interval problems give you ranges with a start and an end and ask how they overlap: merge them, insert one, count how many run at once, keep as many as possible without clashes, or intersect two lists. Almost all of them are solved by sorting first and then making one pass. Sort by start when you need to merge or insert, sort by end when you need to keep the most ranges, and turn the ranges into +1 and -1 events when you need the peak overlap. Sorting makes these O(n log n), and the pass after it is O(n).
By Evin JohnPublished 8 min read
What makes it an interval problem
The input is a list of pairs that stand for stretches of time or space: bookings, shifts, ad slots, ranges of IP addresses, segments on a number line. The question is about how those stretches relate. Two ranges either are apart, touch at an endpoint, overlap partly, or one contains the other. Every technique on this page is a way to avoid comparing all pairs, which would be O(n²).
Ask one question before anything else: do ranges that only touch count as overlapping? With closed ranges, [1, 3] and [3, 5] share the point 3. With half-open ranges, which is how most bookings work, [1, 3) ends just as [3, 5) begins and they do not clash. The answer changes one comparison in every template, from <= to < or back, and getting it wrong is the most common way to fail an otherwise correct solution.
Choosing the move
| The question | Sort by | Then | Cost |
|---|---|---|---|
| Combine everything that overlaps | Start | Extend the last merged range or start a new one | O(n log n) |
| Add one range to an already sorted, disjoint list | Already sorted | Copy left part, absorb overlaps, copy right part | O(n) |
| Keep the most ranges with no clashes, or remove the fewest | End | Keep a range if it starts at or after the last kept end | O(n log n) |
| How many are active at the busiest moment | Event time | Running sum of +1 and -1 | O(n log n) |
| Which room or worker takes each range | Start | Min-heap of end times | O(n log n) |
| Where do two sorted lists overlap | Already sorted | Two pointers, drop the range that ends first | O(n + m) |
Sorting by start versus sorting by end is the decision people mix up. Sorting by start lines ranges up so that anything overlapping the current group comes next, which is what merging needs. Sorting by end is what makes the greedy choice safe: the range that finishes earliest leaves the most room for everything after it, so keeping it can never hurt.
Templates in Python
def insert_interval(intervals, new):
# intervals: sorted by start, no overlaps, closed ends (touching ranges merge)
start, end = new
out = []
i, n = 0, len(intervals)
while i < n and intervals[i][1] < start: # wholly to the left of the new range
out.append(list(intervals[i]))
i += 1
while i < n and intervals[i][0] <= end: # overlaps: absorb it
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
out.append([start, end])
out.extend(list(iv) for iv in intervals[i:]) # wholly to the right
return outInserting [5, 9] into [[1, 2], [4, 6], [8, 10], [13, 15]] gives [[1, 2], [4, 10], [13, 15]]: [4, 6] and [8, 10] both touch the new range and fold into it. Inserting [4, 5] into [[1, 3], [6, 8]] lands between them without merging. The full merge of an unsorted list is covered step by step in Merge Intervals, including the min-heap version of the rooms count.
def min_removals(intervals):
# half-open [start, end): ranges that only touch do not clash
kept = 0
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end: # fits after the last range we kept
kept += 1
last_end = end
return len(intervals) - keptFor [[1, 4], [2, 3], [3, 6], [5, 7], [6, 9]], sorting by end gives [2, 3], [1, 4], [3, 6], [5, 7], [6, 9]. The greedy keeps [2, 3], skips [1, 4], keeps [3, 6], skips [5, 7] and keeps [6, 9], so two removals. Sorting by start instead would keep [1, 4] first and do worse. The same loop answers "maximum number of talks one person can attend" (return kept) and, with closed ranges and a strict > in place of >=, "fewest points that touch every range".
def max_overlap(intervals):
# half-open [start, end): how many ranges are active at the busiest moment
events = []
for start, end in intervals:
events.append((start, 1))
events.append((end, -1))
events.sort() # at a tie, (t, -1) sorts before (t, 1): free first
active = best = 0
for _, change in events:
active += change
best = max(best, active)
return bestThe tie rule lives in the sort. Tuples compare by time and then by the change, so at the same moment an end (-1) is processed before a start (+1). For half-open ranges that is correct: 0, 2) and [2, 4) never run together, and the function returns 1. If touching ranges should count as overlapping, process starts first instead. For the five ranges above, the peak is 2. This is the [difference array idea from the prefix sum pattern applied to sparse times instead of array positions.
def intersect_lists(a, b):
# a and b: each sorted and non-overlapping, closed ends
i = j = 0
out = []
while i < len(a) and j < len(b):
lo = max(a[i][0], b[j][0])
hi = min(a[i][1], b[j][1])
if lo <= hi:
out.append([lo, hi])
if a[i][1] < b[j][1]: # the one that ends first cannot meet anything later
i += 1
else:
j += 1
return outWith [[0, 3], [5, 9], [12, 14]] and [[2, 6], [8, 13]], the result is [[2, 3], [5, 6], [8, 9], [12, 13]]. The pointer rule is the whole proof: the range with the smaller end cannot overlap anything later in the other list, so it is safe to drop.
Templates in JavaScript
function minRemovals(intervals) {
const byEnd = intervals.slice().sort((x, y) => x[1] - y[1]);
let kept = 0;
let lastEnd = -Infinity;
for (const [start, end] of byEnd) {
if (start >= lastEnd) {
kept++;
lastEnd = end;
}
}
return intervals.length - kept;
}
function maxOverlap(intervals) {
const events = [];
for (const [start, end] of intervals) {
events.push([start, 1], [end, -1]);
}
events.sort((x, y) => x[0] - y[0] || x[1] - y[1]); // ends first on a tie
let active = 0;
let best = 0;
for (const [, change] of events) {
active += change;
best = Math.max(best, active);
}
return best;
}
function intersectLists(a, b) {
const out = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const lo = Math.max(a[i][0], b[j][0]);
const hi = Math.min(a[i][1], b[j][1]);
if (lo <= hi) out.push([lo, hi]);
if (a[i][1] < b[j][1]) i++;
else j++;
}
return out;
}Always pass a comparator. Without one, JavaScript sorts by string value, so 10 lands before 9. The event comparator sorts by time, then by change, which puts -1 before +1 on a tie. Copying with slice before sorting avoids reordering the caller's array.
Cost
| Move | Time | Extra space |
|---|---|---|
| Compare every pair | O(n²) | O(1) |
| Sort by start, then merge | O(n log n) | O(n) for the output |
| Insert into a sorted list | O(n) | O(n) for the output |
| Sort by end, greedy keep | O(n log n) | O(1) beyond the sort |
| Event sweep | O(n log n) | O(n) for the events |
| Two-list intersection | O(n + m) | O(n + m) for the output |
Problems to practice the pattern
- [Merge Intervals](/coding-problems/merge-intervals). Sort by start and merge. The best first problem.
- Insert a new range into a sorted schedule. The one-pass template above, without re-sorting.
- Remove the fewest bookings so none overlap. Greedy by end, return the number skipped.
- Can one person attend every meeting? Sort by start and check each neighbour pair. Any overlap means no.
- Fewest rooms for a day of meetings. The event sweep or a heap of end times; both give the peak.
- Common free time across several calendars. Merge all busy ranges, then read the gaps between them.
Before giving the cost of a sort-based answer, the Big O cheat sheet is a quick check of why the sort, not the pass, sets the total. For a change of pattern, the next two pages in this set are graph problems: Evaluate Division and Accounts Merge.
Mistakes
- Not asking whether touching ranges overlap, then using the wrong comparison.
- Sorting by start for the keep-the-most question, which picks long early ranges and loses.
- When merging, setting the end to the new range's end instead of the larger of the two ends.
- In the sweep, letting the sort order of ties happen by accident.
- Sorting without a numeric comparator in JavaScript.
- Mutating the input list in place when the caller still needs it.
- Assuming the input is sorted because the example happened to be.
How to explain it out loud
Fictional example
- Candidate
- First, if one booking ends at 3 and another starts at 3, do they clash? I'll assume not, so these are half-open.
- Candidate
- We want to keep as many bookings as possible. I'll sort by end time and keep a booking whenever it starts at or after the last kept end.
- Interviewer
- Why end time and not start time?
- Candidate
- Whatever the best schedule picks first, swapping it for the booking that ends earliest can't cause a new clash, because that one frees the room sooner. Repeating the argument shows the greedy is never worse. It's n log n for the sort, then linear.
Working through interval sets with Natively
Interval bugs usually come down to one comparison or one sort key, which makes them good for side-by-side checking. Natively can read an interval problem from a screenshot on Mac or Windows and set out an approach and code in its overlay, so you can see whether your tie rule matches. If you rehearse aloud with a friend, it transcribes the session for later review. Read more on the AI interview assistant page.
Questions people ask
How do you solve interval problems?
Sort first, then make one pass. Sort by start to merge or insert, sort by end to keep the most non-overlapping ranges, and turn ranges into +1 and -1 events to find the peak overlap.
How do you check if two intervals overlap?
For closed ranges, a and b overlap when a.start <= b.end and b.start <= a.end. For half-open ranges use strict comparisons, so ranges that only touch do not overlap.
Why sort by end time for the non-overlapping intervals problem?
Keeping the range that finishes earliest leaves the most room for the rest, so the greedy choice is never worse than any other. Sorting by start can keep one long range that blocks several short ones.
What is a sweep line for intervals?
Add an event of +1 at each start and -1 at each end, sort the events by time with a fixed tie rule, and keep a running total. Its highest value is the most ranges active at once.
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.
