Sort the events, then greedily scan with a pointer or counter. Sorting eliminates the need to look back — each decision only depends on the current event and the best previous outcome.
Interval Merging: sort by start; merge when next.start <= prev.end
Activity Selection: sort by end time; greedily take earliest-ending non-overlapping activity
After sorting, each step is O(1) — the greedy choice is always locally optimal
💡 Sort once — then a single linear sweep is all you need. The sorted order guarantees we never need to revisit earlier events.
⚡ Complexity
Sorting
O(n log n)
Sweep / Merge
O(n)
Sorting: O(n log n) — dominates the overall complexity. Sweep / merge: O(n) — one pass through sorted data. Space: O(1) extra for pointer sweep; O(n) if building merged output list.
Problem
Given train schedules with arrivals = [1,2,3,5] and departures = [4,6,7,8], find the minimum platforms needed so no train waits (GFG). Also: given intervals [[1,4],[2,6],[8,10],[15,18]], merge all overlapping ones (LC #56). Both use the same greedy sort idea — process events in order and make the locally optimal choice.
Input (Platforms): arr = [1,2,3,5], dep = [4,6,7,8] · Answer: 3 platforms · Merge: [[1,4],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]