Count the range, then rebuild.
Exploit a small integer range while accounting for the range-sized memory cost.
01 Model the idea
Counting sort counts occurrences of each key, then reconstructs ordered values. It can run in O(n + k) time when n is the number of observations and k is the key range. That advantage depends on a suitably small range: a few widely spaced values can make the count array impractical. This version sorts nonnegative integers and reconstructs values rather than preserving attached record identities.
Counts preserve every occurrence, including duplicates.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
COUNT each nonnegative integer key
VISIT key positions in increasing order
EMIT each key as often as its count03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def counting_sort(values):
if not values: return []
if any(type(value) is not int or value < 0 for value in values):
raise ValueError("Nonnegative integer keys required")
counts = [0] * (max(values) + 1)
for value in values: counts[value] += 1
return [value for value, count in enumerate(counts) for _ in range(count)]
print(counting_sort([3, 1, 2, 1, 0]))[0, 1, 1, 2, 3]
- 1
The key is used as an array index, which is why this implementation rejects negative and noninteger values.
- 2
The reconstruction repeats each key according to its count. Space includes the count array and the returned output list.
- 3
A stable counting sort for records uses cumulative positions and a separate placement pass. That form is useful as a component of radix sorting; do not confuse it with merely expanding a frequency table.
04 Count the cost
O(n + k), where k is the integer key range
O(n + k), including the output
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use Counter to sort a few sparse integer keys without a range-sized array.
Reveal one possible solution +
from collections import Counter
values = [1000000, 2, 2]
counts = Counter(values)
result = [value for value in sorted(counts) for _ in range(counts[value])]
print(result)06 Check your reasoning
What does k represent in the O(n + k) bound?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.