Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 24 / 66

Count the range, then rebuild.

Exploit a small integer range while accounting for the range-sized memory cost.

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
COUNT each nonnegative integer key
VISIT key positions in increasing order
EMIT each key as often as its count

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

counting_sort.py
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]))
↳ EXPECTED OUTPUT
[0, 1, 1, 2, 3]
  1. 1

    The key is used as an array index, which is why this implementation rejects negative and noninteger values.

  2. 2

    The reconstruction repeats each key according to its count. Space includes the count array and the returned output list.

  3. 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

TIME

O(n + k), where k is the integer key range

SPACE

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

A SMALL MISSION

Use Counter to sort a few sparse integer keys without a range-sized array.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What does k represent in the O(n + k) bound?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.