LeetCode 56 Merge Intervals - Why Naive Fails

The trap

Compare every pair of intervals. If they overlap, merge them and repeat.

With nn intervals, there are O(n2)O(n^2) pairs. After each merge, you might need to recheck.

Worst case: O(n3)O(n^3) operations. Sorting first makes this much simpler.