22. Merge Intervals
easyAsked at DoordashCollapse overlapping time windows into the fewest spans — Doordash uses this interval pattern directly in delivery time-window consolidation and Dasher shift-block scheduling.
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: Intervals [1,3] and [2,6] overlap; merged to [1,6].
Example 2
intervals = [[1,4],[4,5]][[1,5]]Explanation: Touching at 4 counts as overlapping.
Approaches
1. Brute force nested comparison
Compare every pair of intervals to find overlaps; merge and restart. O(n^2) passes 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 linear scan
Sort by start time; single pass merging the current interval into the last merged interval whenever they overlap. Classic greedy approach.
- 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];
if (intervals[i][0] <= last[1]) {
last[1] = Math.max(last[1], intervals[i][1]);
} else {
merged.push(intervals[i]);
}
}
return merged;
}Tradeoff:
Doordash-specific tips
Doordash interviewers expect you to immediately connect intervals to real scheduling — 'how would you handle Dasher availability windows that span midnight?' The follow-up is almost always: what if intervals arrive as a stream? That pushes you toward a sorted structure (BST or sorted list with binary search insertion). Name the pattern — greedy after sort — before diving into code.
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 Doordash interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →