21. Merge Intervals
mediumAsked at GrabMerge overlapping intervals — Grab uses this as a sort-plus-sweep classic for scheduling problems.
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^40 <= start_i <= end_i <= 10^4
Examples
Example 1
intervals = [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]Example 2
intervals = [[1,4],[4,5]][[1,5]]Approaches
1. Pairwise overlap check
Repeatedly scan for any overlapping pair and merge them.
- Time
- O(n^2)
- Space
- O(n)
// while changed: scan pairs and merge
// brittle when n growsTradeoff:
2. Sort by start then sweep
Sort by start; sweep once, extending the current interval's end whenever the next interval overlaps.
- Time
- O(n log n)
- Space
- O(n)
function merge(intervals) {
if (intervals.length === 0) return [];
intervals.sort((a, b) => a[0] - b[0]);
const out = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const last = out[out.length - 1];
if (intervals[i][0] <= last[1]) last[1] = Math.max(last[1], intervals[i][1]);
else out.push(intervals[i]);
}
return out;
}Tradeoff:
Grab-specific tips
Grab interviewers love this for ride-window scheduling — frame as collapsing overlapping driver availability blocks in a regional partition.
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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →