Linear-Time Sorting

Counting sort, radix sort and bucket sort beat n log n by not comparing elements — when keys have structure you can exploit.

Intermediate 3 min readLesson 4 of 18 Interview Q&A

The Ω(n log n) bound applies only to comparison sorts. If keys are integers in a known range, or have digits you can inspect, you can sort in linear time by using the key values directly as array indices.

AlgorithmTimeSpaceStableRequirement
Counting sortO(n + k)O(n + k)✓Integer keys in a small range [0, k)
Radix sortO(d·(n + b))O(n + b)✓Keys with d digits in base b
Bucket sortO(n) averageO(n)✓*Keys uniformly distributed

Counting sort

Count how many times each key occurs, turn counts into prefix sums (each key's final position), then place elements — iterating from the end keeps it stable.

20113213
Input [2, 0, 2, 1, 0, 3, 2] → count[key] for keys 0..3. Prefix sums [2, 3, 6, 7] give each key's end position.
int[] countingSort(int[] a, int k) {          // values in [0, k)
    int[] count = new int[k];
    for (int x : a) count[x]++;
    for (int i = 1; i < k; i++) count[i] += count[i - 1];   // prefix sums = end positions
    int[] out = new int[a.length];
    for (int i = a.length - 1; i >= 0; i--)                 // backwards → stable
        out[--count[a[i]]] = a[i];
    return out;
}

Radix sort

Sort by the least significant digit first, then the next, and so on, using a stable sort (counting sort) for each digit. Stability ensures earlier digit orderings survive.

PassInputSorted by
Start170 45 75 90 802 24 2 66—
1170 90 802 2 24 45 75 66ones digit
2802 2 24 45 66 170 75 90tens digit
32 24 45 66 75 90 170 802hundreds digit ✓

With 32-bit integers sorted 8 bits at a time: 4 passes over n elements with 256 buckets — very fast for large arrays of integers, IP addresses, or fixed-length strings.

void radixSort(int[] a) {                     // non-negative ints, base 256
    int[] out = new int[a.length];
    for (int shift = 0; shift < 32; shift += 8) {
        int[] count = new int[257];
        for (int x : a) count[((x >>> shift) & 255) + 1]++;
        for (int i = 0; i < 256; i++) count[i + 1] += count[i];
        for (int x : a) out[count[(x >>> shift) & 255]++] = x;
        System.arraycopy(out, 0, a, 0, a.length);
    }
}

Bucket sort

Distribute n values into n buckets by range (e.g. floats in [0, 1) go to bucket ⌊n·x⌋), sort each small bucket (insertion sort), then concatenate. With uniformly distributed input each bucket holds O(1) elements → O(n) average; adversarial input degrades to the inner sort's worst case.

Key takeaways
  • Non-comparison sorts escape Ω(n log n) by indexing with key values.
  • Counting sort: O(n + k), stable, for small integer ranges.
  • Radix sort: stable digit-by-digit passes, O(d·(n + b)).
  • Bucket sort: O(n) average for uniformly distributed data.
Interview questions
QMaximum gap between successive elements in sorted order, in O(n).hard

Pigeonhole: with n numbers between min and max, the maximum gap is at least (max−min)/(n−1). Use n−1 buckets of that width, tracking only each bucket's min and max. The answer is the largest difference between one non-empty bucket's max and the next non-empty bucket's min.

QWhy must radix sort process the least significant digit first with a stable sort?medium

After sorting by digit d, elements equal at d must stay in the order established by the less significant digits. A stable inner sort guarantees that, so after the last (most significant) pass the whole key is ordered.