Full answer
Problem
Sort a list of records by an integer key in [0, max_key], stably. Then use it to sort non-negative integers digit by digit (LSD radix sort).
Example: students [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)] sorted by grade gives [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]: Ben stays before Eli and Asha before Chen.
Constraints: n <= 10^6, max_key <= 10^6.
Brute force
Any comparison sort, O(n log n). Python's sorted(records, key=...) is stable and is the right tool in everyday code; counting sort matters when n is large and keys are small.
Optimal approach
counts[v]= number of records with keyv.starts[v]= sum ofcountsfor all smaller keys (a prefix sum): the first output index for keyv.- For each record in input order, write it to
out[starts[key]]and incrementstarts[key].
Radix sort for non-negative integers: for exp = 1, 10, 100, ... while some number still has a digit at that place, counting-sort by (x // exp) % 10.
Why it works
The prefix sums reserve a block of output positions for each key, in key order. Scanning the input left to right fills each block in input order, so equal keys keep their relative order: the sort is stable.
Radix sort: after processing digit d, the numbers are sorted by their last d digits. Sorting by the next digit stably keeps that order among numbers whose next digit is equal, so by induction the final pass sorts by all digits. An unstable digit sort would scramble the lower digits.
Complexity
Counting sort: O(n + k) time and space, where k = max_key + 1. Radix sort: O(d x (n + 10)) for d digits. Counting sort becomes poor when k is much larger than n (for example, keys up to 10^9).
Code
def counting_sort(records, key, max_key):
"""Stable counting sort of records by an integer key in [0, max_key]. O(n + k)."""
counts = [0] * (max_key + 1)
for r in records:
counts[key(r)] += 1
starts = [0] * (max_key + 1) # starts[v] = first output index for key v
for v in range(1, max_key + 1):
starts[v] = starts[v - 1] + counts[v - 1]
out = [None] * len(records)
for r in records: # left to right keeps equal keys in input order
out[starts[key(r)]] = r
starts[key(r)] += 1
return out
def radix_sort(nums):
"""LSD radix sort for non-negative integers, using stable counting sort per digit."""
if not nums:
return []
exp = 1
while max(nums) // exp > 0:
nums = counting_sort(nums, key=lambda x: (x // exp) % 10, max_key=9)
exp *= 10
return nums
if __name__ == "__main__":
students = [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)]
by_grade = counting_sort(students, key=lambda s: s[1], max_key=3)
assert by_grade == [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]
assert counting_sort([], key=lambda x: x, max_key=5) == []
assert counting_sort([4, 0, 4, 2], key=lambda x: x, max_key=4) == [0, 2, 4, 4]
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([0, 0]) == [0, 0]
assert radix_sort([]) == []
print("all tests passed")Save as a45_counting_sort.py and run python3 a45_counting_sort.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty input. All keys equal. Keys at both ends of the range. Negative keys need an offset (subtract the minimum). Radix sort with zeros only ([0, 0]). Large ranges with few records: use a comparison sort or radix sort with a larger base instead.
Pattern
Non-comparison sorting with counts and prefix sums. Stability as a building block for multi-key sorting: sort by the secondary key, then stably by the primary key. Bucket sort follows the same idea for evenly distributed real values.
def counting_sort(records, key, max_key):
"""Stable counting sort of records by an integer key in [0, max_key]. O(n + k)."""
counts = [0] * (max_key + 1)
for r in records:
counts[key(r)] += 1
starts = [0] * (max_key + 1) # starts[v] = first output index for key v
for v in range(1, max_key + 1):
starts[v] = starts[v - 1] + counts[v - 1]
out = [None] * len(records)
for r in records: # left to right keeps equal keys in input order
out[starts[key(r)]] = r
starts[key(r)] += 1
return out
def radix_sort(nums):
"""LSD radix sort for non-negative integers, using stable counting sort per digit."""
if not nums:
return []
exp = 1
while max(nums) // exp > 0:
nums = counting_sort(nums, key=lambda x: (x // exp) % 10, max_key=9)
exp *= 10
return nums
if __name__ == "__main__":
students = [("Asha", 3), ("Ben", 1), ("Chen", 3), ("Dara", 2), ("Eli", 1)]
by_grade = counting_sort(students, key=lambda s: s[1], max_key=3)
assert by_grade == [("Ben", 1), ("Eli", 1), ("Dara", 2), ("Asha", 3), ("Chen", 3)]
assert counting_sort([], key=lambda x: x, max_key=5) == []
assert counting_sort([4, 0, 4, 2], key=lambda x: x, max_key=4) == [0, 2, 4, 4]
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort([0, 0]) == [0, 0]
assert radix_sort([]) == []
print("all tests passed")Stable counting sort with a key function and prefix-sum start positions; LSD radix sort calls it once per decimal digit.
Complexity
Time: O(n + k) for counting sort; O(d * (n + 10)) for radix sort. Space: O(n + k). The Omega(n log n) lower bound applies only to comparison sorts.
By level
Fresher: Explains counting with an array of counts and shows stability on the student list. Should state when counting sort is a poor choice.
Mid: Implements the prefix-sum version, builds radix sort and explains why stability is required. Handles negative keys with an offset.
Senior: Discusses the comparison lower bound, memory and cache effects for large k, radix base choice and multi-key sorting. Can explain why the comparison lower bound does not apply here.
Key points
- Count, prefix-sum into start positions, place left to right
- Left-to-right placement makes it stable
- O(n + k), good when keys are small
- Radix sort needs a stable per-digit sort
- Comparison sorts are bounded by n log n; counting sort is not a comparison sort
Common mistakes
- Rebuilding output from counts and losing the records attached to keys
- Placing right to left with forward start positions and breaking stability
- Using counting sort with a huge key range
- Forgetting an offset for negative keys
Follow-ups
- How would you sort by two keys using stable sorts?
- How would you handle negative integers in radix sort?
- When is bucket sort a good choice?
Tips
- Define stability with the student example
- Explain the prefix-sum step
- State the conditions where counting sort wins
Evaluation rubric
- Correct stable counting sort
- Correct radix sort reasoning
- Correct complexity in n and k
- Explains when not to use it