Loading section...

Merge Intervals: Sort First, Scan Once

Concepts: pyMergeIntervals, pyIntervalSort

The algorithm is three lines of logic after sorting. Initialize a result list with the first interval. For each subsequent interval: if its start is less than or equal to the current end (overlapping), extend the current end to the maximum of both ends. Otherwise, this interval does not overlap, so push it onto the result as a new standalone interval. That is the entire algorithm. The reason it feels elegant is that sorting eliminates all backward comparisons. You are always merging with the last interval in the result, never with something earlier. Step-by-Step Code Walk through this with [[1,3],[2,6],[8,10],[15,18]]. After sort (already sorted): merged = [[1,3]]. Process [2,6]: start=2 <= current_end=3, so extend to max(3,6)=6. merged = [[1,6]]. Process [8,10]: start=8 > current_end=6, n