Greedy Algorithms8 sections · 316 units
Open in Course

The Interval Pattern

Sort first, scan second

Most interval problems follow this pattern:

1.1. Sort: by start time (for merging) or end time (for selection)

2.2. Scan: left to right, maintaining state

3.3. Decide: at each interval: merge, extend, or start new

Without sorting first, you would need O(n2)O(n^2) comparisons to check all pairs. Sorting lets you process intervals in order, making local decisions that lead to global optimality. The pattern runs in O(nlog⁡n)O(n \log n) time (sorting) and typically O(1)O(1) space if done in-place.