Skip to main content

23. Merge Intervals

mediumAsked at Notion

Collapse overlapping time ranges into non-overlapping spans — the algorithm Notion's calendar view runs every render to merge back-to-back event blocks into single visual bars without double-counting covered time.

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

Explanation: Intervals [1,3] and [2,6] overlap; merged to [1,6].

Example 2

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

Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Approaches

1. Sort then sweep

Sort by start time; iterate and either extend the last merged interval's end or push a new interval — one pass after sorting.

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:

2. Sort then sweep (immutable output)

Same sweep but builds fresh arrays rather than mutating result entries — safer in functional pipelines.

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

Tradeoff:

Notion-specific tips

Notion calendar and timeline views must merge overlapping time blocks for clean rendering. Interviewers watch whether you sort first without prompting — if you don't, they'll ask why adjacent-only comparisons are insufficient. Also handle the edge case where intervals[i][1] < last[1] (one interval fully contained in another).

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

Practice these live with InterviewChamp.AI →