Problem
FAANG · LeetCode #56

Merge Intervals — three-stage drill

1The ProblemMedium

Merge Intervals

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

merge every group of overlapping intervals into oneinput[1,3][2,6][8,14][9,11][15,18]135791113151719merged[1,6][8,14][15,18]return[[1,6],[8,14],[15,18]]
Examples
[[1,3],[2,6],[8,14],[9,11],[15,18]]→ [[1,6],[8,14],[15,18]][[1,4],[4,5]]→ [[1,5]]

constraintSort by start first; then a single left-to-right sweep merges in place.

2The PatternTIME O(n log n) · SPACE O(n)

Intervals

Given a pile of ranges, sort them by start — now any overlap is a neighbour, so a single left→right pass handles them.

sort the ranges by start, then sweep once01234567891011[7,9][2,5][1,3][8,10]given: a pile of ranges in any order
Problems using this pattern
3The SolutionRESULT → [[1,6],[8,14],[15,18]]

Step through it

the input — not yet sortedinput[8,14][1,3][9,11][15,18][2,6]135791113151719merged
the input as given — not yet sorted
Step 1 / 12
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent