#56

Merge Intervals

Medium Sort by start

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Merge all overlapping intervals and return the non-overlapping result.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: merge overlapping intervals.

Why this works: after sorting by start, an interval either overlaps the last merged one (extend it) or starts a new one.

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

[1,3]+[2,6] → [1,6][8,10] new, [15,18] new

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Setting end = next.end instead of max(end, next.end) — a nested interval would shrink the merged one.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n) for the output.
Topic: Sorting
🎬 Episodes 24–28: video coming soon