Coding problem · Medium · Intervals

Merge Intervals

Medium Algorithms & data structures Most askedSeen at Meta, Google, Amazon, Bloomberg, Salesforce

Given an array of intervals where intervals[i] = [start, end], merge all overlapping intervals and return the non-overlapping intervals that cover the same ranges, sorted by start. Touching intervals ([1,4] and [4,5]) overlap.

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

Hints

Hint 1

Sort by start time. Then each interval either extends the last merged one or starts a new one.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n log n) · Space O(n)

After sorting by start, keep a result list. If the current interval starts at or before the last merged end, extend that end to max(lastEnd, end) (it might be fully contained); otherwise append a new interval.

Reference solution

function merge(intervals) {
  const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
  const out = [];
  for (const [s, e] of sorted) {
    const last = out[out.length - 1];
    if (last && s <= last[1]) last[1] = Math.max(last[1], e);
    else out.push([s, e]);
  }
  return out;
}

Common mistakes

  • Using the current interval's end instead of max(...) — [1,4],[2,3] must stay [1,4].