Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Counting Sort proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Count bounded integer keys and reconstruct order in time proportional to input plus key range. Learn the algorithm's preconditions, state transition, correctness argument, Python cost model, and transfer from one focused drill to a full Interview Problem.
Recognize it when
Consider Counting Sort when the prompt's constraints and required operations match this shape: Count bounded integer keys and reconstruct order in time proportional to input plus key range.

Sign in to save your code and progress across devices. The lesson and problem statement remain public.
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.
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.
def count_trace(values,maximum):
counts=[0]*(maximum+1);trace=[]
for value in values:counts[value]+=1;trace.append(counts.copy())
return traceImplement count_trace(values,maximum). Return the count array after each nonnegative value.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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.
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 outputImplement stable_counting_sort(records,maximum). Sort [key,label] by nonnegative key while preserving equal-key order.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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.
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 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Counting Sort proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Counting Sort complete workflow | O(n + r) | O(n + r) | Count the offset integer domain and expand frequencies from the minimum through maximum. |
O(r) for the focused Sort a Bounded Integer Range implementation.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Verify algorithm preconditions such as sorted input, nonnegative weights, acyclicity, or admissible heuristics before applying it.
Prevent it: State and verify this precondition before coding: The comparison, key domain, stability need, and memory constraints match the selected ordering method.
Avoid
def counting_sort(values):
passUse instead
def counting_sort(values):
if not values:
return []
low, high = min(values), max(values)
counts = [0] * (high - low + 1)
for value in values:
counts[value - low] += 1
result = []
for offset, frequency in enumerate(counts):
result.extend([low + offset] * frequency)
return resultWhere you will hit this: Sort a Bounded Integer Range(opens in a new tab)
Emits each distinct value once and loses duplicate multiplicity.
Prevent it: Preserve this proof obligation: The resolved prefix, suffix, rank, digit pass, or bucket remains in its documented final relation.
Avoid
def counting_sort(values):
if not values:return []
low=min(values); counts=[0]*(max(values)-low+1)
for value in values:counts[value-low]+=1
return [low+i for i,count in enumerate(counts) if count]Use instead
def counting_sort(values):
if not values:
return []
low, high = min(values), max(values)
counts = [0] * (high - low + 1)
for value in values:
counts[value - low] += 1
result = []
for offset, frequency in enumerate(counts):
result.extend([low + offset] * frequency)
return resultWhere you will hit this: Sort a Bounded Integer Range(opens in a new tab)
Include visited state, boundary cases, recursion depth, and hidden copying costs in correctness and complexity analysis.
Prevent it: Count every sort, slice, copy, membership check, heap update, and recursive frame before claiming O(n + r).
Avoid
def counting_sort(values):
if not values:return []
low=min(values); counts=[0]*(max(values)-low+1)
for value in values:counts[value-low]+=1
return [low+i for i,count in enumerate(counts) if count]Use instead
def counting_sort(values):
if not values:
return []
low, high = min(values), max(values)
counts = [0] * (high - low + 1)
for value in values:
counts[value - low] += 1
result = []
for offset, frequency in enumerate(counts):
result.extend([low + offset] * frequency)
return resultWhere you will hit this: Friends of Appropriate Ages(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27