Skip to main content

23. Merge Intervals

mediumAsked at Etsy

Collapse overlapping time ranges into non-overlapping intervals — the core algorithm Etsy uses to merge seller promotional sale windows before applying discounts.

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]]

Example 2

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

Approaches

1. Brute force (repeated passes)

Repeatedly scan the list, merging any pair of overlapping intervals, until no merges happen in a full pass. O(n^2) passes in the worst case.

Time
O(n^2)
Space
O(n)
function merge(intervals) {
  let merged = [...intervals];
  let changed = true;
  while (changed) {
    changed = false;
    const next = [];
    let used = new Array(merged.length).fill(false);
    for (let i = 0; i < merged.length; i++) {
      if (used[i]) continue;
      let [s, e] = merged[i];
      for (let j = i + 1; j < merged.length; j++) {
        if (used[j]) continue;
        if (merged[j][0] <= e) {
          e = Math.max(e, merged[j][1]);
          used[j] = true;
          changed = true;
        }
      }
      next.push([s, e]);
    }
    merged = next;
  }
  return merged;
}

Tradeoff:

2. Sort then single scan

Sort intervals by start time. Walk through once: if the current interval overlaps the last merged interval (current.start <= last.end), extend last.end to the max of both ends. 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];
    const [start, end] = intervals[i];
    if (start <= last[1]) {
      last[1] = Math.max(last[1], end);
    } else {
      result.push([start, end]);
    }
  }
  return result;
}

Tradeoff:

Etsy-specific tips

Etsy's promotions engine merges overlapping sale windows so a listing isn't double-discounted. Walk the interviewer through why sort-then-scan reduces a 2D problem to 1D: after sorting by start, you only ever need to compare the current interval against the last merged one. Be ready to extend this to 'insert a new interval into an already-merged list' (LC 57).

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

Practice these live with InterviewChamp.AI →