Skip to main content

20. Merge Intervals

mediumAsked at Yelp

Merge a list of overlapping intervals — Yelp uses sort + sweep to test whether candidates can collapse adjacent business-hours ranges before scaling to geo-cell overlap merging.

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^4
  • 0 <= start_i <= end_i <= 10^4

Examples

Example 1

Input
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output
[[1,6],[8,10],[15,18]]

Example 2

Input
intervals = [[1,4],[4,5]]
Output
[[1,5]]

Approaches

1. Nested compare and union

Repeatedly scan for overlapping pairs and merge them until no overlaps remain.

Time
O(n^2)
Space
O(n)
let res = [...intervals], changed = true;
while (changed) {
  changed = false;
  outer: for (let i = 0; i < res.length; i++)
    for (let j = i+1; j < res.length; j++)
      if (res[i][1] >= res[j][0] && res[i][0] <= res[j][1]) {
        res[i] = [Math.min(res[i][0], res[j][0]), Math.max(res[i][1], res[j][1])];
        res.splice(j, 1); changed = true; break outer;
      }
}
return res;

Tradeoff:

2. Sort by start, then sweep

After sorting by start, walk once; extend the current merged interval whenever the next one overlaps, otherwise push and reset.

Time
O(n log n)
Space
O(n)
function merge(intervals) {
  if (!intervals.length) return [];
  intervals.sort((a, b) => a[0] - b[0]);
  const out = [intervals[0]];
  for (let i = 1; i < intervals.length; i++) {
    const top = out[out.length - 1];
    if (intervals[i][0] <= top[1]) top[1] = Math.max(top[1], intervals[i][1]);
    else out.push(intervals[i]);
  }
  return out;
}

Tradeoff:

Yelp-specific tips

Yelp will pivot to geo indexing — be ready to discuss how interval merging extends to collapsing overlapping geohash cells when computing nearby-business coverage.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Merge Intervals and other Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →