Skip to main content

18. Merge Intervals

mediumAsked at Swiggy

Merge all overlapping intervals in a list and return the result.

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 the non-overlapping intervals that cover all the input intervals.

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. Repeated pair-merge

Repeatedly scan and merge any overlapping pair until none remain.

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

Tradeoff:

2. Sort and sweep

Sort by start time, then walk through; either extend the current merged interval's end or push a new one when the next start exceeds the last end.

Time
O(n log n)
Space
O(n)
function merge(intervals) {
  intervals.sort((a, b) => a[0] - b[0]);
  const res = [];
  for (const iv of intervals) {
    if (res.length && iv[0] <= res[res.length - 1][1]) {
      res[res.length - 1][1] = Math.max(res[res.length - 1][1], iv[1]);
    } else {
      res.push(iv.slice());
    }
  }
  return res;
}

Tradeoff:

Swiggy-specific tips

Swiggy treats interval merging as a proxy for collapsing overlapping courier-shift windows; they want clean sort-then-sweep with no off-by-one on the equality case.

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 Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →