Typorithm · medium

Merge Intervals

merge-intervalsintervalssort-by-startoverlapextend
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Merge Intervals

0%

Intervals

Sort by start, then sweep; if the next interval overlaps the last merged one, extend its end, otherwise append it.

Sorting by start guarantees that any interval overlapping a previous one is adjacent in the order.

Compare each interval with the last merged interval: if its start is within that interval, they overlap.

On overlap, extend the last interval's end to the maximum of the two; otherwise, start a new merged interval.

01

Sort intervals by start.

02

Overlap when start <= last end.

03

Extend end with Math.max.

function merge(intervals) {
  intervals.sort((a, b) => a[0] - b[0]);
  const merged = [];

  for (const [start, end] of intervals) {
    const last = merged[merged.length - 1];
    if (last && start <= last[1]) {
      last[1] = Math.max(last[1], end);
    } else {
      merged.push([start, end]);
    }
  }

  return merged;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Sort by start

Sorting by start groups overlapping intervals together.

intervals.sort((a, b) => a[0] - b[0])

2. Previous interval

Compare each interval against the most recently merged one.

const last = merged[merged.length - 1]

3. Overlap test

An overlap occurs when the new start is within the last interval.

if (last && start <= last[1]) {

4. Extend end

Stretch the last interval's end to cover the overlap.

last[1] = Math.max(last[1], end)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Merge Intervals: Lesson & Practice · Typorithm | ApplyDjinn