RecapDifficulty: Advanced1 min

Recap: Intervals

Sort by start and compare with the last merged interval; walk two lists with two pointers; sweep the events to count how many at once.

Interval problems turn on order. Sorted by start, an interval can only overlap the last one merged, so merging is one pass; two sorted lists intersect by walking a pointer through each; and counting how many run at once sorts the starts and ends together and keeps a running count. Whether touching intervals overlap is a decision about the times, not the code:

Interval questions and how each is answered
QuestionSort byPassTouching intervalsCost
Merge overlapsStartCompare with the last mergedMerge when closedO(n log n)
Insert one intervalAlready sortedBefore, overlapping, afterMerge when closedO(n)
Intersect two listsAlready sortedTwo pointers, earlier end movesOverlap when closedO(n + m)
Most at onceEvent timeRunning count, or a min-heap of endsApart when half-openO(n log n)

Sorting by end is the slip to watch for: a long interval that starts early arrives last and merges into the wrong neighbour, with no error. Extending with the larger end, not the current one, keeps an interval that sits inside another from shrinking it.