Merge Intervals

medium

Merge all overlapping intervals — classic FAANG sorting problem

Merge Intervals

Key Insight

Sort by start time, then merge overlapping by comparing prev.end with curr.start

Step 1Input Intervals
Already sorted by start in this example
[1,3]
0
[2,6]
1
[8,10]
2
[15,18]
3

Unsorted intervals: [[1,3], [2,6], [8,10], [15,18]]

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Merge Intervals

Sort by start time, then merge overlapping by comparing prev.end with curr.start

  1. Input Intervals

    Unsorted intervals: [[1,3], [2,6], [8,10], [15,18]]

  2. Start with First

    Add [1,3] to result. Now check next interval.

  3. [2,6] Overlaps with [1,3]

    2 ≤ 3 (curr.start ≤ prev.end) → overlap! Merge to [1, max(3,6)] = [1,6].

  4. [8,10] No Overlap

    8 > 6 (curr.start > prev.end) → no overlap. Add [8,10] as new.

  5. [15,18] No Overlap

    15 > 10 → no overlap. Add [15,18].