52. Merge Intervals
mediumAsked at RedditMerge overlapping intervals. Reddit uses this canonical interval problem to test sort + scan — the same shape used when merging consecutive vote-window aggregations into a single hot-score period.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Reddit loops.
- Glassdoor (2026-Q1)— Reddit data-platform on-site question.
- Blind (2025-11)— Reported on Reddit infra-team rounds.
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]]Example 2
intervals = [[1,4],[4,5]][[1,5]]Approaches
1. Pairwise merge
Repeatedly scan list, merge any overlapping pair, until stable.
- Time
- O(n^2)
- Space
- O(n)
// Anti-pattern: quadratic and convergence is delicate.Tradeoff: Slow and bug-prone.
2. Sort by start + scan (optimal)
Sort intervals by start. Walk; if current overlaps with last merged, extend its end; else append.
- Time
- O(n log n)
- Space
- O(n) output
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const out = [];
for (const [s, e] of intervals) {
if (out.length && out[out.length - 1][1] >= s) {
out[out.length - 1][1] = Math.max(out[out.length - 1][1], e);
} else {
out.push([s, e]);
}
}
return out;
}Tradeoff: Dominated by the sort. The merge scan is linear.
Reddit-specific tips
Reddit interviewers grade on remembering to sort by start. Bonus signal: discuss the >= vs. > question (do touching intervals merge? Yes, per the example [1,4],[4,5] -> [1,5]).
Common mistakes
- Sorting by end instead of start.
- Using > instead of >= for overlap (misses touching intervals).
- Mutating the input and confusing yourself.
Follow-up questions
An interviewer at Reddit may pivot to one of these next:
- Insert Interval (LC 57) — given sorted list + new interval.
- Non-overlapping intervals (LC 435).
- Meeting rooms (LC 252) / Meeting rooms II (LC 253).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why sort by start, not end?
Sorting by start lets us greedily extend the most recent merged interval. Sort by end works for other problems (scheduling).
When would Math.max be needed for end?
When the current interval is fully inside the last merged one, e.g., last=[1,10], current=[2,3].
Practice these live with InterviewChamp.AI
Drill Merge Intervals and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →