Merge Intervals solution explained
To merge intervals, sort them by start, then sweep once: if the next interval starts at or before the end of the last merged one, stretch that end; otherwise start a new merged interval. Sorting costs O(n log n) and the sweep is O(n), so the whole Merge Intervals solution runs in O(n log n) time.
By Evin JohnPublished 7 min read
The task, restated
Each item in the input is a pair of numbers, a start and an end, with the start no larger than the end. Think of them as bookings on a timeline. Some bookings overlap, some sit inside others, and some stand alone. Produce a new list where every group of overlapping bookings has become one booking that covers the whole group, and nothing in the output overlaps anything else.
| Input | Output | What happened |
|---|---|---|
| [[8, 10], [1, 4], [3, 6], [12, 12]] | [[1, 6], [8, 10], [12, 12]] | 1 to 4 and 3 to 6 overlap; the rest stand alone |
| [[2, 5], [5, 7]] | [[2, 7]] | They touch at 5, which counts as overlapping when ends are inclusive |
| [[1, 10], [2, 3], [4, 8]] | [[1, 10]] | Both smaller ranges sit inside the first |
| [[0, 1]] | [[0, 1]] | A single interval is already merged |
The most useful clarifying question is about touching ends. With closed ranges, [2, 5] and [5, 7] share the point 5 and merge. With half-open ranges, as in calendar slots where a meeting from 2 to 5 frees the room at 5, they stay separate. The difference is a single comparison operator, so settle it early. Also ask whether the input is already sorted and whether you may modify it in place.
How interviewers use it
Merge Intervals is a favorite in rounds for product engineers because it looks like real work: calendars, booking systems, log windows, IP ranges. It checks whether you think to sort before writing loops, and whether you handle the containment case where one range swallows the next. Interviewers also like that it opens into a family of follow-ups without a new setup.
- Insert one new range into a sorted, non-overlapping list. No sort is needed: copy ranges that end before the new one, absorb the ones that overlap it, then copy the rest. That is O(n).
- Can one person attend every meeting? Sort by start and check whether any meeting starts before the previous one ends.
- Fewest rooms for all meetings. Sort by start and keep a min-heap of end times; the heap's largest size is the answer. Code for this is below.
- Intersect two sorted lists of free time. Walk both with two pointers and advance whichever range ends first.
- Ranges keep arriving. A balanced tree or a sorted container keyed by start lets you merge each new range with its neighbors in O(log n) plus the merges.
Brute force: merge any overlapping pair until none remain
Two ranges [a, b] and [c, d] overlap when a is at most d and c is at most b. A direct approach scans all pairs, merges the first overlapping pair it finds, and starts over. Each scan is O(n²) and there can be up to n merges, so the worst case is O(n³). It is correct, and it is a reasonable opening line, but it should not be your final answer.
def merge_by_pairs(ranges):
spans = [list(r) for r in ranges]
merged_any = True
while merged_any:
merged_any = False
for i in range(len(spans)):
for j in range(i + 1, len(spans)):
a, b = spans[i], spans[j]
if a[0] <= b[1] and b[0] <= a[1]:
spans[i] = [min(a[0], b[0]), max(a[1], b[1])]
del spans[j]
merged_any = True
break
if merged_any:
break
return sorted(spans)The efficient approach: sort, then sweep
Sort the ranges by their start. Now walk them in order, keeping a result list. Compare each range with the last range in the result. If its start is at or before that range's end, they overlap, so set the last range's end to the larger of the two ends. If not, there is a gap, and since every later range starts even further right, nothing later can reach back across it. Append the range as a new entry.
The max on the end is the line people forget. Without it, [1, 10] followed by [2, 3] would shrink the merged range to end at 3.
def merge_ranges(ranges):
merged = []
for start, end in sorted(ranges, key=lambda r: r[0]):
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return mergedfunction mergeRanges(ranges) {
const ordered = ranges.map((r) => [r[0], r[1]]).sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of ordered) {
const last = merged[merged.length - 1];
if (last && start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
merged.push([start, end]);
}
}
return merged;
}For half-open ranges, change the overlap test from <= to <. Everything else stays the same.
The rooms follow-up in code
import heapq
def rooms_needed(meetings):
ends = [] # end times of meetings currently using a room
for start, end in sorted(meetings):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end)
else:
heapq.heappush(ends, end)
return len(ends)This version treats meetings as half-open, so a meeting that ends at 3 frees its room for one that starts at 3. Swap <= for < if the interviewer says otherwise.
Time and space
| Version | Time | Extra space |
|---|---|---|
| Repeated pairwise merging | O(n³) worst case | O(n) |
| Sort, then sweep | O(n log n) | O(n) for the output, plus the sort's own space |
| Insert into an already sorted list | O(n) | O(n) for the output |
| Fewest rooms with a heap | O(n log n) | O(n) for the heap |
Edge cases
- An empty list returns an empty list.
- A single range comes back unchanged.
- Ranges that touch exactly at an endpoint: merged or not, depending on the agreed definition.
- A range fully inside another, which needs the max on the end.
- Ranges that are all identical.
- Unsorted input in reverse order, which is why you sort even when the examples look sorted.
- Zero-length ranges such as [12, 12], which are valid and can merge with a neighbor that covers them.
Mistakes to avoid
- Sorting in JavaScript without a comparator, which sorts [10, 2] before [9, 1] because it compares text.
- Setting the merged end to the new range's end instead of the larger of the two.
- Comparing each range only with the one before it in the input rather than with the last merged range.
- Mutating the caller's list without saying so. Copying first costs little and avoids surprises.
- Skipping the touching-ends question, then arguing about it after the code is written.
Explaining it in the room
Fictional example
- Candidate
- If the ranges are sorted by start, a range can only overlap the group I am currently building, never an older one, because everything earlier ended before a gap.
- Candidate
- So I sort, then for each range either extend the current group's end, using the max in case it is contained, or close the group and open a new one.
- Candidate
- The sort dominates at n log n, and the sweep is linear. I am treating touching ranges as overlapping; if these were calendar slots I would switch the comparison to strict.
Related walkthroughs
Longest Substring Without Repeating Characters is another one-pass sweep, this time with a window that grows and shrinks. Valid Parentheses tracks open items with a stack instead of a sorted list. The heap in the rooms follow-up appears again in Top K Frequent Elements. Every problem in this set is listed on the coding problems hub.
Where Natively fits
For practice on Mac or Windows, Natively can capture an interval problem from your screen, read it, and suggest the sort-then-sweep idea along with the touching-ends question you should ask. Because it also transcribes your mock round, you can reread how you explained the containment case and how long you spent before writing code. Details are on the AI interview assistant page.
Questions people ask
How do you merge overlapping intervals?
Sort the intervals by start. Walk them in order, and if an interval starts at or before the end of the last merged one, extend that end to the larger of the two ends; otherwise start a new merged interval.
What is the time complexity of Merge Intervals?
O(n log n) for the sort plus O(n) for the sweep, so O(n log n) overall. If the input is already sorted, the merge itself is linear.
Should intervals that only touch be merged?
It depends on whether the ranges are closed or half-open. With closed ranges, [2, 5] and [5, 7] share a point and merge; with calendar-style half-open ranges they do not. Ask before coding.
What follow-ups come after Merge Intervals?
Common ones are inserting a new interval into a sorted list, checking whether one person can attend all meetings, finding the fewest rooms needed, and intersecting two lists of intervals.
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.
