17. Merge Intervals
mediumAsked at GlassdoorGlassdoor's salary-range bands overlap across job titles and geographies — merging those intervals cleanly is a real backend task, which is why this sort-and-sweep problem shows up regularly in their coding screens.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of intervals where intervals[i] = [starti, endi], 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 <= starti <= endi <= 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 because 2 <= 3, so they merge into [1,6].
Example 2
intervals = [[1,4],[4,5]][[1,5]]Explanation: Intervals that touch at a single point are considered overlapping.
Approaches
1. Brute force — repeated linear scan
Repeatedly scan the list and merge any overlapping pair until no merges occur. O(n^2) passes, impractical for large inputs.
- Time
- O(n^2)
- Space
- O(n)
function merge(intervals) {
let changed = true;
while (changed) {
changed = false;
const next = [];
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;
}
}
next.push([s, e]);
}
intervals = next;
}
return intervals;
}Tradeoff:
2. Sort then sweep
Sort intervals by start time. Walk once: if the current interval overlaps the last merged one, extend it; otherwise push a new entry. O(n log n) sort dominates.
- 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];
const [start, end] = intervals[i];
if (start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
result.push([start, end]);
}
}
return result;
}Tradeoff:
Glassdoor-specific tips
Glassdoor tests merge-intervals specifically because salary data arrives in overlapping bands from multiple sources and must be deduped before display. Interviewers expect you to sort first — if you skip that step they'll ask why. Mention the edge case where two intervals touch exactly at one endpoint (e.g., [1,4] and [4,5]) and confirm your overlap condition handles it with <=, not <.
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 Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →