Skip to contentKEEP THE CRAFTTHE SANCTUARY

Bucket Sort

Map numeric values into ordered ranges, sort within each range, then concatenate in range order. Distinguish a valid bucket mapping from favorable distribution assumptions and include local sorting cost.

1 practice exercise2 interview problems

Recognize it when Values have a known numeric scale that yields useful small buckets.

Checking your account…

Bucket Sort Code Labs

Map Values into Ordered Buckets

Bucket sort partitions a numeric range into ordered regions. If every value in bucket i precedes every value in bucket j for i < j, concatenating sorted buckets is globally sorted.

Choose Bucket Width and Range

The mapping must cover minimum and maximum values without boundary overflow. Bucket width, count, and offset should follow the known domain rather than an unexplained constant.

Trace Bucket Assignments

Reference
def bucket_trace(values,width):
    buckets={};trace=[]
    for value in values:
        index=value//width;buckets.setdefault(index,[]).append(value);trace.append([[key,buckets[key].copy()] for key in sorted(buckets)])
    return trace
Practice

Implement bucket_trace(values,width). Return bucket contents after each nonnegative integer is assigned by value // width. width must be a positive integer.

Public tests

  • Map values by bucket width

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

Trace Bucket Assignments

def bucket_trace(values,width):
    buckets={};trace=[]
    for value in values:
        index=value//width;buckets.setdefault(index,[]).append(value);trace.append([[key,buckets[key].copy()] for key in sorted(buckets)])
    return trace

Assignment Order Is Not Output Order

Predict the existing assignment trace for width 3. Its last bucket contains [7,6] on purpose: tracing assignment is distinct from the second Lab that sorts each bucket.

Step Executed statement State Why
Assign 7 index=value//width;buckets.setdefault(index,[]).append(value) index=2, buckets={2: [7]} Width 3 bucket 2 represents values 6 through 8.
Assign 2 index=value//width;buckets.setdefault(index,[]).append(value) buckets={2: [7], 0: [2]} A smaller range may arrive later than a larger one.
Record ordered keys trace.append([[key,buckets[key].copy()] for key in sorted(buckets)]) snapshot keys=[0, 2] The trace displays range order, not dictionary arrival order.
Assign 6 index=value//width;buckets.setdefault(index,[]).append(value) bucket 2=[7, 6] The bucket still needs a local sort; assignment alone does not establish value order.
Print Output
print(bucket_trace([7, 2, 6], 3)) [[[2, [7]]], [[0, [2]], [2, [7]]], [[0, [2]], [2, [7, 6]]]]

A good interview explanation includes the mapping proof and occupancy assumption separately. Correct ranges guarantee correctness, while balanced bucket sizes explain potential speed.

Sort Within Each Bucket

Buckets are not automatically sorted. Use insertion sort for small expected buckets or the language sort for clarity, then concatenate bucket indexes in order.

Sort Values by Buckets

Reference
def bucket_sort(values,width):
    buckets={}
    for value in values:buckets.setdefault(value//width,[]).append(value)
    result=[]
    for index in sorted(buckets):result.extend(sorted(buckets[index]))
    return result
Practice

Implement bucket_sort(values,width). Return sorted nonnegative integers without mutating input. width must be a positive integer.

Public tests

  • Order buckets then their contents

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

Sort Values by Buckets

def bucket_sort(values,width):
    buckets={}
    for value in values:buckets.setdefault(value//width,[]).append(value)
    result=[]
    for index in sorted(buckets):result.extend(sorted(buckets[index]))
    return result

Know When Buckets Degenerate

Expected near-linear behavior depends on a favorable distribution. If all values land in one bucket, inner sorting falls back to O(n log n) or worse. Memory also grows with allocated empty buckets.

Explain It in an Interview

Say: “This mapping preserves cross-bucket order; I sort only within buckets and concatenate them.” State distribution assumptions, treatment of negatives and endpoints, expected cost, and the worst-case degeneration.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Dictionary-backed bucket sortO(n + b log b + sum(m_i log m_i))O(n log n + b log b)b occupied buckets, m_i their sizes; hashing assumes average constant lookup.

Space

O(n + b) core values/buckets/output; bucket_trace can retain O(n^2) copied output cells.

Assumptions

  • Near-linear expected behavior needs a distribution premise and a suitable number of buckets.
  • The implemented sorted(buckets) costs O(b log b); unlike direct fixed-index buckets, it is not a free pass.
  • After every insertion, bucket_trace sorts up to n occupied keys and copies all values seen: worst-case O(n^2 log(n+1)) time and O(n^2) retained cells, separate from the sorting core.

Invariants Worth Saying Aloud

  1. Each input appears in exactly one bucket.
  2. For positive width, every value in an earlier floor-division bucket precedes every value in a later bucket.
  3. A bucket remains unsorted until its local ordering step is performed.

When To Use Or Avoid Bucket Sort

Use It When

  • Choose a positive width and distribute values with floor division.
  • Use buckets when their expected occupancy makes local sorts cheaper than a full comparison sort.

Choose Another Tool When

  • If values all fall in one bucket, local sorting dominates.
  • A sparse huge domain should not force an enormous array of empty buckets.

Common Pitfalls

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

Creating aliased bucket lists

[[]] * 3 repeats one list reference. Appending to bucket 1 unexpectedly changes every bucket.

Prevent it: Allocate one independent list per bucket.

Avoid

buckets = [[]] * 3

Use instead

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

Concatenating insertion-order buckets

If bucket 2 was created before bucket 0, dictionary insertion order places larger values first.

Prevent it: Iterate numeric bucket keys in increasing order.

Avoid

output = [v for bucket in buckets.values() for v in sorted(bucket)]

Use instead

output = [v for key in sorted(buckets) for v in sorted(buckets[key])]

Assuming assignment also sorts a bucket

Values 4 then 3 both belong to width-5 bucket 0, but retain arrival order [4,3].

Prevent it: Sort locally before concatenating ranges.

Avoid

output = bucket.copy()

Use instead

output = sorted(bucket)

Reviewed References

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