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)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 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. maximum must be a nonnegative integer; every value must be an integer in 0..maximum.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def count_trace(values,maximum):
counts=[0]*(maximum+1);trace=[]
for value in values:counts[value]+=1;trace.append(counts.copy())
return traceThe 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. |
| 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.
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. maximum must be a nonnegative integer; every key must be an integer in 0..maximum.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 outputChoose 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 |
|---|---|---|---|
| Stable counting sort | O(n + k) | O(n + k) | k=maximum+1, including empty slots. |
O(n + k) for stable output plus counts; count_trace copies k slots per input, using O(nk) trace storage.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
counts[value] += 1counts[value - low] += 1Where you will hit this: Sort a Bounded Integer Range(opens in a new tab)
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.
output = [key for key, count in enumerate(counts) if count]output = [key for key, count in enumerate(counts) for _ in range(count)]Where you will hit this: Sort a Bounded Integer Range(opens in a new tab)
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.
for record in records:
counts[record[0]] -= 1
output[counts[record[0]]] = recordfor record in reversed(records):
counts[record[0]] -= 1
output[counts[record[0]]] = recordWhere 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