Skip to contentKEEP THE CRAFTTHE SANCTUARY

Radix Sort

Order nonnegative integers by stable least-significant-digit passes. Explain why equal current digits must preserve lower-digit order, how missing high digits act as zero, and what base and digit count cost.

1 practice exercise8 interview problems

Recognize it when Keys have a bounded digit representation rather than arbitrary comparison behavior.

Checking your account…

Radix Sort Code Labs

Sort One Digit at a Time

Radix sort orders keys by repeated digit passes rather than pairwise comparison. Least-significant-digit sorting begins at the lowest place and preserves earlier digit work through stability.

Keep Each Digit Pass Stable

Items sharing the current digit must retain their prior relative order. Stable buckets or counting placement ensures higher-place passes do not destroy the ordering already established by lower places.

Trace Stable Digit Passes

Reference
def radix_pass_trace(values):
    output=values.copy();trace=[];place=1;maximum=max(output,default=0)
    while maximum//place:
        buckets=[[] for _ in range(10)]
        for value in output:buckets[(value//place)%10].append(value)
        output=[value for bucket in buckets for value in bucket];trace.append(output.copy());place*=10
    return trace
Practice

Implement radix_pass_trace(values). For nonnegative integers, return the list after each stable base-10 digit pass.

Public tests

  • Preserve prior digit order within buckets

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

Trace Stable Digit Passes

def radix_pass_trace(values):
    output=values.copy();trace=[];place=1;maximum=max(output,default=0)
    while maximum//place:
        buckets=[[] for _ in range(10)]
        for value in output:buckets[(value//place)%10].append(value)
        output=[value for bucket in buckets for value in bucket];trace.append(output.copy());place*=10
    return trace

Preserve Ones Order When Tens Tie

Predict both rows returned by the existing digit-pass Lab. The first row is intentionally not fully sorted; stability makes the second row sufficient.

Step Executed statement State Why
Ones classification buckets[(value//place)%10].append(value) digit 2 bucket=[32, 12], digit 4=[14] Appending retains input order among equal ones digits.
Flatten first pass output=[value for bucket in buckets for value in bucket] output=[32, 12, 14] The output is ordered by ones, not yet by complete values.
Advance place place*=10 place=10 The next digit becomes the new primary priority.
Tens classification buckets[(value//place)%10].append(value) digit 1 bucket=[12, 14], digit 3=[32] Stable tens ties retain the previously established ones order.
Stop while maximum//place: place=100, maximum//place=0 Every significant decimal position has been processed.
Print Output
print(radix_pass_trace([32, 14, 12])) [[32, 12, 14], [12, 14, 32]]

The missing higher digits of smaller nonnegative values are zero. If adding signed values later, explain a separate sign treatment rather than extending this digit proof unchanged.

Choose Base and Number of Passes

With base b and d digits, work including initialization is O(n + d(n + b)). A larger base reduces passes but increases bucket memory; count passes from the maximum key representation.

Radix Sort Nonnegative Integers

Reference
def radix_sort(values):
    output=values.copy();place=1;maximum=max(output,default=0)
    while maximum//place:
        buckets=[[] for _ in range(10)]
        for value in output:buckets[(value//place)%10].append(value)
        output=[value for bucket in buckets for value in bucket];place*=10
    return output
Practice

Implement radix_sort(values). Return a sorted copy of nonnegative integers using stable base-10 passes.

Public tests

  • Sort variable digit lengths without mutation

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

Radix Sort Nonnegative Integers

def radix_sort(values):
    output=values.copy();place=1;maximum=max(output,default=0)
    while maximum//place:
        buckets=[[] for _ in range(10)]
        for value in output:buckets[(value//place)%10].append(value)
        output=[value for bucket in buckets for value in bucket];place*=10
    return output

Handle Signs and Variable Lengths

Missing higher digits act as zero for nonnegative integers. Signed values need a deliberate strategy such as separately sorting magnitudes of negatives and reversing their order; direct digit extraction alone is insufficient.

Explain It in an Interview

Say: “Each stable digit pass refines order without breaking lower-place ties. After every digit of the maximum key, full numeric order is established.” State base, sign domain, stability, and O(n + d(n + b)) cost.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Base-b LSD radix sortingO(n + d(n + b))O(n + d(n + b))Initialization copies and scans n values even when d=0 for all-zero input; d digit passes use base b (10 here).

Space

O(n + b) working storage; the pass-trace Lab retains O(dn) output cells.

Assumptions

  • Digit extraction for very large Python integers has arithmetic bit cost.
  • An all-zero or empty input needs no digit pass and already satisfies order.

Invariants Worth Saying Aloud

  1. After place p, the output is ordered by all processed low-order digits.
  2. Within equal current-digit buckets, prior relative order is preserved.
  3. Every value appears exactly once in each pass.

When To Use Or Avoid Radix Sort

Use It When

  • Use stable digit passes for a known nonnegative integer domain.
  • Choose a base with a deliberate tradeoff between pass count and bucket storage.

Choose Another Tool When

  • A direct nonnegative-digit scheme cannot sort signed values without a separate sign strategy.
  • For small general-purpose lists, maintained comparison sorting is usually clearer.

Common Pitfalls

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

Sharing every digit bucket

Aliased lists place every value into every bucket, duplicating the output.

Prevent it: Use a comprehension to create independent buckets.

Avoid

buckets = [[]] * 3

Use instead

buckets = [[] for _ in range(3)]

Reversing equal-digit arrival order

On the tens pass, [12,13] have the same digit 1. Prepending each arrival turns their correct ones ordering into [13,12].

Prevent it: Append within each digit bucket to preserve prior ordering.

Avoid

for value in values: bucket.insert(0, value)

Use instead

for value in values: bucket.append(value)

Stopping after the ones digit

For [31,13,12], ones sorting gives [31,12,13]; stopping there misses the higher digit. A tens-only pass from the original input also leaves 13 before 12.

Prevent it: Complete stable passes from least to most significant digit. This two-digit example retains the ones result as input to the tens pass.

Avoid

output = sorted(values, key=lambda value: value % 10)

Use instead

output = sorted(values, key=lambda value: value % 10)
output = sorted(output, key=lambda value: value // 10)

Reviewed References

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