Stage 1 · Code
Arrays & Hashing
Sorting Tricks
Know when to sort — and when counting sort or bucket sort beats O(n log n).
7 min readLeetCode Patterns for InterviewsCode
The Pattern
Sorting unlocks many patterns: two-pointer techniques require a sorted array; anagram grouping uses sorted strings as keys; and often sorting by one dimension makes the second dimension tractable. When the value range is bounded, counting sort gives O(n).
Time Complexity Comparison
Bucket sort
O(n)
Group by frequency
Comparison sort
O(n log n)
General purpose (Go's sort.Slice)
Counting sort
O(n + k)
Integer values in bounded range [0..k]
Bubble sort
O(n²)
Avoid — worst-case quadratic
| When | Sort type | Complexity |
|---|---|---|
| General ordering needed | Comparison sort (Go's sort.Slice) | O(n log n) |
| Integer values in bounded range [0..k] | Counting sort | O(n+k) |
| Group by frequency | Bucket sort by count | O(n) |
| Strings as map keys | Sort each string | O(m · k log k) where m=words, k=length |
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.