19. Merge Intervals
mediumAsked at SoFiMerge all overlapping intervals — SoFi uses this constantly because loan-statement billing periods and recurring transaction windows are interval problems in disguise.
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
[[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]Example 2
[[1,4],[4,5]][[1,5]]Approaches
1. Brute force
Repeatedly scan pairs for overlap and merge until no more merges possible.
- Time
- O(n^2)
- Space
- O(n)
function merge(intervals) {
let changed = true;
while (changed) {
changed = false;
outer: for (let i = 0; i < intervals.length; i++)
for (let j = i+1; j < intervals.length; j++) {
const [a,b] = intervals[i], [c,d] = intervals[j];
if (a <= d && c <= b) {
intervals[i] = [Math.min(a,c), Math.max(b,d)];
intervals.splice(j, 1);
changed = true;
break outer;
}
}
}
return intervals;
}Tradeoff:
2. Sort + sweep
Sort by start, then walk through and merge into the last result if current.start <= last.end, else push as new interval.
- Time
- O(n log n)
- Space
- O(n)
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const result = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const last = result[result.length - 1];
if (intervals[i][0] <= last[1]) {
last[1] = Math.max(last[1], intervals[i][1]);
} else {
result.push(intervals[i]);
}
}
return result;
}Tradeoff:
SoFi-specific tips
SoFi engineers see this pattern weekly — interest-accrual periods, autopay schedules, and statement closing dates all merge as intervals, so candidates who immediately reach for sort+sweep score well.
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 SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →