Sub topic 7
Counting Sort Cost: O(n + k) and the Range Problem
This chapter assumes you know Big-O notation and have seen the stable, prefix-sum version of counting sort from the previous chapter. Here you will count exactly what that algorithm spends, in time and memory, and see why the size of the key range decides whether counting sort is a good choice.
Where the Time Goes
Stable counting sort makes three passes. Two of them depend on the number of items, n. One depends on the key range 0..k.
| Pass | What it does | Cost |
|---|---|---|
| Histogram | Read each item once and add 1 to `counts[key]` | O(n) |
| Prefix sums | Walk the count array once | O(k) |
| Placement | Read each item again and write it to its slot | O(n) |
Adding these gives O(n + k) time. No pass compares two items with each other, so the Ω(n log n) lower bound for comparison sorts does not apply.
Memory follows the same pattern. The output array holds n slots and the count array holds k + 1 counters, so the extra space is O(n + k).
When "Linear" Is Actually Linear
The bound O(n + k) means linear time only when k grows no faster than n, that is, when k = O(n). Here are three common cases:
- k much smaller than n. Examples are sorting a million bytes (k = 255) or a million exam scores (k = 100). The prefix-sum pass costs almost nothing, and counting sort is very fast.
- k about the same as n. The cost is still O(n), but the count array now takes as much memory as the data does.
- k much larger than n. The
kterm takes over. Sorting 1,000 arbitrary 32-bit integers needs a count array with about 4.3 billion entries. At 8 bytes per counter that is roughly 32 GiB of memory, all spent to sort a thousand numbers.
The script below estimates both the work and the size of the count array for each case:
def counting_sort_estimate(n, k, bytes_per_counter=8):
"""Rough step count and count-array size for stable counting sort."""
work = 2 * n + (k + 1) # two passes over items, one over counts
mem_mib = (k + 1) * bytes_per_counter / 2**20
return work, mem_mib
cases = [(1_000_000, 255), (1_000_000, 1_000_000), (1_000, 2**32 - 1)]
for n, k in cases:
work, mem = counting_sort_estimate(n, k)
print(f"n={n:>9,} k={k:>13,} steps~{work:>13,} counts={mem:>10,.3f} MiB")In the last case, an O(n log n) comparison sort would need only about 10,000 comparisons.
Shrinking the Range
The range that matters is the span from the smallest key to the largest, not the size of the largest key. If you subtract the minimum key first, k becomes max - min:
def effective_range(keys):
"""Size of the count array needed after shifting keys to start at 0."""
lo, hi = min(keys), max(keys)
return hi - lo
timestamps = [1_700_000_120, 1_700_000_003, 1_700_000_450, 1_700_000_003]
print(effective_range(timestamps)) # 447, not 1.7 billionFinding the minimum and maximum takes one extra O(n) pass, so the total cost stays O(n + k). The shift does not help when the keys are spread across a wide span. For that case, the next chapters split each key into small digits and run counting sort once per digit.
Common Mistakes
- Sizing the count array from the type instead of the data. Allocating 2^32 counters because the keys are 32-bit integers, when the actual span is small.
- Forgetting the shift. If you compute
minbut then index with the raw key, the code raises anIndexErroror quietly wastes memory. - Ignoring memory when k is about n. Time stays linear, but a count array the size of the input can push data out of the CPU cache and slow every pass.
Exercise
You need to sort 2,000,000 records whose integer keys all fall between 5,000,000,000 and 5,000,000,800. What value of k should counting sort use, and what is the running time?
Show answer
Subtract the minimum key, 5,000,000,000. The keys then fall in 0..800, so k = 800. The running time is O(n + k) = O(2,000,000 + 800), which is effectively O(n), and the count array has only 801 entries.
Exercise
You need to sort 100 integers with values in 0..10,000,000. Which is cheaper: counting sort or merge sort?
Show answer
Merge sort. Counting sort does about 2·100 + 10,000,001 ≈ 10 million steps and allocates 10 million counters. Merge sort does about 100 · log2(100) ≈ 700 comparisons. Because k is much larger than n, the k term dominates.