Skip to main content

56. Merge Intervals

mediumAsked at Snap

Snap Stories expire at varying times and the timeline renderer collapses overlapping active-story windows into continuous display segments — merge intervals is exactly that computation.

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

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 pairwise merge

Compare every pair of intervals, merge if overlapping, repeat until no merges occur. O(n^2) passes — avoid in interviews.

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

Tradeoff:

2. Sort then linear sweep

Sort by start time, then walk the array once: if the current interval overlaps the last merged interval (start <= last end), extend; otherwise push a new interval. O(n log n) due to sort, O(1) extra beyond output.

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

Tradeoff:

Snap-specific tips

Snap frames this as 'active story windows on a timeline — merge the segments a user would see as one continuous strip.' The sort-then-sweep answer is expected; the follow-up is handling streaming intervals arriving in real time (use a sorted tree or segment tree).

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

Practice these live with InterviewChamp.AI →