Skip to contentKEEP THE CRAFTTHE SANCTUARY

Counting Sort

Replace key comparisons with frequencies in a small integer domain. Track cumulative positions for stable record placement and count both the domain size and output storage.

1 practice exercise1 interview problem

Recognize it when Keys are integers bounded by a modest maximum or a compact offset range.

Checking your account…

Counting Sort Code Labs

Count a Bounded Key Domain

Counting sort replaces comparisons with a frequency array indexed by keys. It is appropriate only when keys map to a reasonably small known integer domain.

Turn Counts into Output

For plain values, emit each key its recorded number of times. This costs O(n + k), where k is the domain size, even if few keys occur.

Trace Frequency Counts

Reference
def count_trace(values,maximum):
    counts=[0]*(maximum+1);trace=[]
    for value in values:counts[value]+=1;trace.append(counts.copy())
    return trace
Practice

Implement count_trace(values,maximum). Return the count array after each nonnegative value. maximum must be a nonnegative integer; every value must be an integer in 0..maximum.

Public tests

  • Increment exactly one domain slot

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Frequency Counts

def count_trace(values,maximum):
    counts=[0]*(maximum+1);trace=[]
    for value in values:counts[value]+=1;trace.append(counts.copy())
    return trace

Observe Frequencies Before Turning Them into Positions

The existing frequency Lab records a full count array after every input value. Predict each slot, including the unused key 2. The next Lab converts these frequencies into positions.

Step Executed statement State Why
Allocate counts=[0]*(maximum+1);trace=[] counts=[0, 0, 0] Maximum 2 requires three slots, even if key 2 never occurs.
First key 1 counts[value]+=1 counts=[0, 1, 0] Only the slot representing key 1 changes.
Key 0 counts[value]+=1 counts=[1, 1, 0] Zero is a valid key, not a missing-record sentinel.
Second key 1 counts[value]+=1;trace.append(counts.copy()) last row=[1, 2, 0] Multiplicity grows to two; earlier snapshots must remain unchanged.
Print Output
print(count_trace([1, 0, 1], 2)) [[0, 1, 0], [1, 1, 0], [1, 2, 0]]

For stable records, cumulative counts are not final frequencies after placement: they are moving end boundaries. Explain which meaning a count array currently has before reading or changing it.

Preserve Stability with Positions

Convert counts to cumulative end positions, traverse records from right to left, decrement the key’s position, and place the record there. Reverse traversal preserves equal-key input order.

Stable Counting Sort Records

Reference
def stable_counting_sort(records,maximum):
    counts=[0]*(maximum+1)
    for key,_ in records:counts[key]+=1
    for index in range(1,len(counts)):counts[index]+=counts[index-1]
    output=[None]*len(records)
    for record in reversed(records):
        key=record[0];counts[key]-=1;output[counts[key]]=record.copy()
    return output
Practice

Implement stable_counting_sort(records,maximum). Sort [key,label] by nonnegative key while preserving equal-key order. maximum must be a nonnegative integer; every key must be an integer in 0..maximum.

Public tests

  • Use cumulative output positions

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Stable Counting Sort Records

def stable_counting_sort(records,maximum):
    counts=[0]*(maximum+1)
    for key,_ in records:counts[key]+=1
    for index in range(1,len(counts)):counts[index]+=counts[index-1]
    output=[None]*len(records)
    for record in reversed(records):
        key=record[0];counts[key]-=1;output[counts[key]]=record.copy()
    return output

Choose Counting Sort or Comparison Sort

Choose counting sort when k is comparable to n and keys are bounded integers. Use comparison sorting when the domain is huge, sparse, unknown, or keys need arbitrary ordering. Offset indexes deliberately for negative keys.

Explain It in an Interview

Say: “The count array summarizes the bounded key domain. Cumulative counts locate output positions, and reverse placement preserves stability.” State O(n + k) time and O(n + k) space rather than calling it simply linear.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Stable counting sortO(n + k)O(n + k)k=maximum+1, including empty slots.

Space

O(n + k) for stable output plus counts; count_trace copies k slots per input, using O(nk) trace storage.

Assumptions

  • Negative keys require an explicit offset scheme; direct Python negative indexing is not such a scheme.
  • The trace snapshots cost O(nk), unlike the untraced counting phase.

Invariants Worth Saying Aloud

  1. Each processed record increments exactly one key frequency.
  2. Cumulative counts give exclusive end positions for keys.
  3. Right-to-left placement fills equal-key slots from the end, preserving original order.

When To Use Or Avoid Counting Sort

Use It When

  • Use counting when k domain slots are affordable relative to input size n.
  • Use frequency expansion for plain values, cumulative positions for stable records.

Choose Another Tool When

  • A huge sparse key range makes scanning and allocating every slot wasteful.
  • Arbitrary comparable objects belong with comparison sorting.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Indexing negative keys without an offset

Python counts[-1] updates the last slot, conflating -1 with a legitimate positive key.

Prevent it: Translate signed values by a known minimum before indexing a compact domain.

Avoid

counts[value] += 1

Use instead

counts[value - low] += 1

Ignoring duplicate frequencies

Emitting a key once per nonzero bucket returns [1,2] instead of the multiset [1,2,2].

Prevent it: Emit exactly the stored number of copies.

Avoid

output = [key for key, count in enumerate(counts) if count]

Use instead

output = [key for key, count in enumerate(counts) for _ in range(count)]

Filling cumulative end positions from the wrong direction

Forward traversal places the first equal record into the last slot and reverses ties.

Prevent it: Traverse records in reverse when decrementing exclusive end positions.

Avoid

for record in records:
    counts[record[0]] -= 1
    output[counts[record[0]]] = record

Use instead

for record in reversed(records):
    counts[record[0]] -= 1
    output[counts[record[0]]] = record

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.