#56
Medium
Greedy

Merge Intervals

Merge all overlapping intervals.

ArraySorting

Pattern fit

Sorting by start time turns the problem into a single greedy scan where you either extend the current merged interval or commit it and start a new one.

Key observation

Once intervals are sorted by start, overlap decisions only depend on the current merged interval's end.

Target complexity

O(n log n) / O(n)

How to break down the solution cleanly

1

Sorting by start time turns the problem into a single greedy scan where you either extend the current merged interval or commit it and start a new one.

2

Once intervals are sorted by start, overlap decisions only depend on the current merged interval's end.

3

Identify the local choice that seems to preserve the most future flexibility.

4

Sort or preprocess if that makes the choice testable.

Reference implementation

Python
# Generic pattern template
items.sort(key=priority)
answer = 0
for item in items:
    if can_take(item):
        take(item)
        answer = update(answer)

Common pitfalls

warning

Forgetting to sort before merging.

warning

Failing to append the last active interval after the loop.

Common follow-ups

How would you count removed intervals instead of returning the merge?

What if intervals are inclusive on both ends?

Continue with related problems

Build repeatable depth inside the Greedy cluster before moving on.

view_weekBack to the pattern page
LeetCode 56. Merge Intervals Guide | Interview AiBox