Builds onBig-O and complexity
01The idea
Many problems get easier once the input is in order. Sorting costs O(n log n), and it gives you facts you can use afterwards:
- Equal values sit next to each other, so you can count or remove duplicates in one pass.
- Close values sit next to each other, so the closest pair is always a pair of neighbours.
- The smallest value is first and the largest is last.
- You can walk the array with two pointers from both ends, or binary search it.
So a common plan has two steps. Sort the input, then do one O(n) pass that relies on the order. The total is O(n log n), which is fast enough for 100,000 items or more.
You can also sort by any key you choose. Sort intervals by their start, words by their length, or people by height and then by name. In Python pass key=. In Java pass a comparator.
02How to spot it
Think about sorting when:
- the brute force checks every pair, and the pair you want is "close" or "equal" in some way
- the order of the input does not matter to the answer, only the values do
- a greedy choice needs the items from smallest to largest, or by end time, or by some other key
- the problem mentions overlaps, ranges or meetings, which call for sorting by start time
Do not sort when the answer depends on the original order, such as "the first index where". If you need the original positions after sorting, sort pairs of value and index instead of the bare values.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue