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
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.
Once intervals are sorted by start, overlap decisions only depend on the current merged interval's end.
Identify the local choice that seems to preserve the most future flexibility.
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
Forgetting to sort before merging.
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.