Skip to main content

27. Merge Intervals

mediumAsked at Expedia

Merge all overlapping intervals into the fewest continuous ranges — Expedia applies this to consolidate adjacent layover windows in an itinerary into a single unbroken block.

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
  • intervals[i].length == 2
  • 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]]

Explanation: [1,3] and [2,6] overlap and merge to [1,6].

Example 2

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

Approaches

1. Brute force repeated scan

Repeatedly scan the list looking for any overlapping pair and merge them until no overlaps remain.

Time
O(n^2)
Space
O(n)
function merge(intervals) {
  let changed = true;
  while (changed) {
    changed = false;
    intervals.sort((a, b) => a[0] - b[0]);
    const next = [intervals[0]];
    for (let i = 1; i < intervals.length; i++) {
      const last = next[next.length - 1];
      if (intervals[i][0] <= last[1]) {
        last[1] = Math.max(last[1], intervals[i][1]);
        changed = true;
      } else {
        next.push(intervals[i]);
      }
    }
    intervals = next;
  }
  return intervals;
}

Tradeoff:

2. Sort once then linear scan

Sort by start time. Scan once: if the current interval overlaps the last merged one, extend its end; otherwise push a 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:

Expedia-specific tips

Expedia expects you to jump to the sort-once approach and explain the two cases clearly: overlap (extend last) vs. no overlap (push new). They often follow up by asking how you'd handle streaming intervals arriving out of order — a good answer mentions an insertion-sort variant or a balanced BST keyed on start time.

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

Practice these live with InterviewChamp.AI →