synopsis · Linear patterns · chapter 19
Sorting
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Sorting puts equal and nearby values next to each other, so duplicates, overlaps and gaps show up in one linear scan.
- use it when
Intervals, duplicates, closest pairs, pair sums without indices, "form the largest…": ask first — would sorting expose the structure?
- cost
Comparison sorts can't beat Ω(n log n). Merge/heap: O(n log n) always. Quicksort: O(n log n) expected, O(n²) worst. Counting: O(n + k).
- template
Numbers:
Arrays.sort(nums). Objects:list.sort(comparingInt(f).thenComparing(g))— stable TimSort keeps earlier orders as tie-breakers. - trap
(a, b) -> a - boverflows:MIN_VALUE - 1wraps to a big positive. UseInteger.compare(a, b)orComparator.comparingInt. - trap
A fixed first/last pivot makes quicksort O(n²) on sorted input; a 2-way partition crawls on all-equal input. Random pivot + 3-way split fixes both.
- trap
int[]takes no comparator. For descending ints, sort and read backwards, or box toInteger[]withCollections.reverseOrder(). - pro tip
Only the k-th or top k? Don't sort everything: quickselect is O(n) on average, a size-k heap is O(n log k).
- pro tip
Sorting a linked list? Merge sort: no random access needed, and merging only relinks nodes — O(1) extra space bottom-up.
Shaky on a card? Open the chapter or flip its recall cards.