56. Merge Intervals
mediumAsked at AirbnbCollapse overlapping date ranges into clean availability windows — the exact interval-merge logic Airbnb's calendar engine runs every time a host blocks dates or a guest extends a stay.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4
Examples
Example 1
intervals = [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]Explanation: [1,3] and [2,6] overlap since 2 <= 3, so they merge into [1,6].
Example 2
intervals = [[1,4],[4,5]][[1,5]]Explanation: Intervals [1,4] and [4,5] are considered overlapping (touching boundary).
Approaches
1. Brute force
For each interval, scan all others to find overlaps and merge. Repeat until stable.
- Time
- O(n^2)
- Space
- O(n)
function merge(intervals) {
let changed = true;
while (changed) {
changed = false;
const result = [];
const used = new Array(intervals.length).fill(false);
for (let i = 0; i < intervals.length; i++) {
if (used[i]) continue;
let [s, e] = intervals[i];
for (let j = i + 1; j < intervals.length; j++) {
if (used[j]) continue;
const [s2, e2] = intervals[j];
if (s2 <= e && e2 >= s) {
s = Math.min(s, s2);
e = Math.max(e, e2);
used[j] = true;
changed = true;
}
}
result.push([s, e]);
}
intervals = result;
}
return intervals;
}Tradeoff:
2. Sort then sweep
Sort by start time, then do a single left-to-right sweep: extend the current interval's end or start a new one. Classic greedy interval merge.
- Time
- O(n log n)
- Space
- O(n)
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const merged = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const last = merged[merged.length - 1];
const [start, end] = intervals[i];
if (start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
merged.push([start, end]);
}
}
return merged;
}Tradeoff:
Airbnb-specific tips
Airbnb recruiters confirm this appears in nearly every on-site loop — framed as 'consolidate blocked-off dates on a host calendar.' They grade on edge cases: adjacent intervals (touching but not overlapping), a single-element input, and already-sorted vs unsorted input. Talk through the sort step first and explain why it reduces the problem to a single pass.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Merge Intervals and other Airbnb interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →