Linear-Time In-Place Digit Sort
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement sort_digits(digits: bytearray) -> None to reorder a bytearray of base-10 digits (0 through 9) into non-decreasing order in place, returning None.
In production, digits holds 100,000,000 (10^8) single-byte values (100 MB), and your implementation must work for any buffer length N (0 <= N <= 10^9). Because only ten distinct byte values can appear, avoid O(N log N) comparison sorting and any O(N) auxiliary copy; instead, tally digit frequencies in a fixed 10-slot table (O(1) extra RAM) and overwrite digits in O(N) time.
Alongside the code, be ready to analyze storage layouts (such as 8-byte integers, 1-byte unsigned integers, and packed 4-bit nibbles), CPU cache-line and DRAM bandwidth ceilings, and realistic wall-clock execution time on contemporary hardware.
Examples
Example 1
Input: digits = bytearray([7, 1, 5, 1, 0, 8, 5, 1])
Call: sort_digits(digits) # returns None
Output: digits == bytearray([0, 1, 1, 1, 5, 5, 7, 8])
Walk-through: Scanning the 8 bytes records frequencies 0: 1, 1: 3, 5: 2, 7: 1, and 8: 1 (with 0 for 2, 3, 4, 6, 9). Writing each digit back according to its count produces [0, 1, 1, 1, 5, 5, 7, 8] directly inside digits.
Example 2
Input: digits = bytearray([9, 3, 9, 3, 3])
Call: sort_digits(digits) # returns None
Output: digits == bytearray([3, 3, 3, 9, 9])
Walk-through: Even when eight of the ten digits never occur, the 10-counter table skips zero-frequency buckets cleanly and writes three 3s followed by two 9s in place.
Constraints
0 <= len(digits) <= 10^9(target benchmark size:10^8bytes).- Every element satisfies
0 <= digits[i] <= 9. digitsmust be mutated in place andsort_digitsmust returnNone.- Time complexity:
O(N). - Auxiliary space complexity:
O(1)(a fixed 10-counter table with noO(N)temporary slices or copies, even when allNbytes are identical).
Step-by-step walkthrough
Understand the problem and the memory budget
We are given a
bytearraynameddigitsof lengthN(withN = 100,000,000in the scenario, and0 <= N <= 10^9in general), where every element is a single digit from0to9inclusive. We must sortdigitsin place in non-decreasing order and returnNone, usingO(N)time andO(1)extra space.A Python
bytearrayis a mutable, contiguous array of raw bytes where each slot stores one integer in0..255using 1 byte of memory. That means10^8digits take100,000,000bytes (100 MB, or about95.4 MiB), and iterating overdigitsyields plain Pythonintvalues one by one.Why a general comparison sort falls short
The tempting one-liner is a general-purpose comparison sort:
def sort_digits_naive(digits: bytearray) -> None: digits[:] = sorted(digits)While functionally correct on tiny inputs, it violates both design goals at
N = 10^8:- Too much work (
O(N log N)time): Any comparison-based sort needs on the order ofN * log2(N)comparisons. AtN = 10^8,log2(10^8)is about26.6, so it performs roughly2.7 * 10^9comparisons even though only ten distinct values exist. - Too much memory (
O(N)extra space):sorted(digits)builds a temporary Pythonlistholding10^88-byte object pointers — roughly800 MBof extra RAM just to sort100 MBof bytes!
- Too much work (
Key idea: ten frequency counters capture the entire sorted array
Because every element is a bare integer in
0..9with no attached metadata, two4s are completely indistinguishable. That means the final sorted array depends only on how many times each digit0..9appears:counts = [c0, c1, c2, ..., c9] sorted = (c0 copies of 0), then (c1 copies of 1), ..., then (c9 copies of 9)This simplifies counting sort (sorting by tallying key frequencies instead of comparing elements pairwise) to two clean linear passes:
- Pass 1 (Count): Read
digitsfrom start to finish and incrementcounts[value]for each byte. - Pass 2 (Overwrite): Walk
digitsfrom index0toN - 1, writingcounts[0]zeros,counts[1]ones, ..., up tocounts[9]nines.
Notice why we do not need the textbook version of counting sort that computes prefix sums and copies elements into a second output array: prefix sums exist to keep equal keys stable (preserving the original order of attached records). With bare digits, regenerating values directly from
countssorts in place withO(1)extra memory.- Pass 1 (Count): Read
Phase 1: Count how often each digit appears
Allocate a fixed list of 10 integer counters initialized to
0, then scandigitsonce:# counts[d]: frequency of digit d (0..9), e.g. [1, 3, 0, 0, 0, 2, 0, 1, 1, 0]. # Fixed length 10 guarantees O(1) auxiliary memory regardless of len(digits). counts: List[int] = [0] * 10 # Pass 1: scan the bytearray once to tally how many times each digit occurs. for value in digits: counts[value] += 1On counter width in lower-level languages:
N = 10^8(and evenN = 10^9) fits inside a signed 32-bit integer (max ~ 2.14 * 10^9), but using ten 64-bit unsigned integers (uint64_t[10], only80bytes total!) is the safest systems practice so larger inputs never overflow. Pythonints have arbitrary precision and never overflow.Phase 2: Overwrite the bytearray in sorted order
Once Pass 1 finishes,
countsholds everything we need to know about the input, so we can safely overwritedigitsin place from left to right using a cursorwrite_pos:# Pass 2: overwrite `digits` from left to right in ascending digit order 0..9. # Safe to overwrite in place because Pass 1 already captured all frequencies, # and we write byte-by-byte to avoid allocating any O(N) temporary slice buffer. write_pos = 0 for digit in range(10): frequency = counts[digit] for _ in range(frequency): digits[write_pos] = digit write_pos += 1Why write byte by byte instead of a slice assignment like
digits[write_pos : write_pos + frequency] = bytes([digit]) * frequency? Becausebytes([digit]) * frequencyallocates a temporarybytesobject of lengthfrequency! If all10^8digits are0, that temporary buffer takes100 MB, silently breaking ourO(1)space guarantee.Trace Example 1 step by step
Walk through
digits = bytearray([7, 1, 5, 1, 0, 8, 5, 1])(N = 8):Pass 1 (read left to right): see 7 -> counts[7] = 1 see 1 -> counts[1] = 1 see 5 -> counts[5] = 1 see 1 -> counts[1] = 2 see 0 -> counts[0] = 1 see 8 -> counts[8] = 1 see 5 -> counts[5] = 2 see 1 -> counts[1] = 3 Final counts = [1, 3, 0, 0, 0, 2, 0, 1, 1, 0] (d: 0 1 2 3 4 5 6 7 8 9) Pass 2 (overwrite using write_pos): digit 0 (freq 1): write 0 at pos 0 -> [0, _, _, _, _, _, _, _], write_pos = 1 digit 1 (freq 3): write 1 at pos 1, 2, 3 -> [0, 1, 1, 1, _, _, _, _], write_pos = 4 digits 2..4 : 0 iterations -> unchanged digit 5 (freq 2): write 5 at pos 4, 5 -> [0, 1, 1, 1, 5, 5, _, _], write_pos = 6 digit 6 (freq 0): 0 iterations -> unchanged digit 7 (freq 1): write 7 at pos 6 -> [0, 1, 1, 1, 5, 5, 7, _], write_pos = 7 digit 8 (freq 1): write 8 at pos 7 -> [0, 1, 1, 1, 5, 5, 7, 8], write_pos = 8 digit 9 (freq 0): 0 iterations -> unchangedBecause
sum(counts) == 8,write_posfinishes at8 == len(digits)and every slot is written once.Hardware analysis: memory layout, bandwidth, and realistic runtime
1. Memory representation choices (
N = 10^8): Because the per-element CPU logic is tiny, runtime is heavily governed by how many bytes travel between main memory (DRAM) and the CPU:Packed 4-bit nibbles (2 digits/byte) 50 MB (minimum practical footprint; needs bit shifts/masks) bytearray / uint8_t (1 byte/digit) 100 MB (sweet spot: 1 byte per digit, zero unpacking) int32_t (4 bytes/digit) 400 MB (4x more memory traffic for no benefit) int64_t (8 bytes/digit) 800 MB (8x more memory traffic) Python list[int] 800 MB+ (10^8 8-byte pointers to singleton int objects)2. Cache and DRAM bandwidth floor: Main memory transfers data in 64-byte cache lines (fixed 64-byte blocks), and sequential scans let hardware prefetchers stream lines ahead of the CPU:
- Pass 1 reads
100 MBsequentially from DRAM (countsis only 80 bytes and stays pinned in L1 cache or CPU registers). - Pass 2 writes
100 MBsequentially. With streaming (non-temporal) stores (special instructions that write full cache lines straight to memory without reading old bytes first), Pass 2 costs100 MBof DRAM traffic (200 MBtotal). With normal stores, modifying an uncached line triggers read-for-ownership (the CPU first reads the old 64-byte line from DRAM before overwriting and later flushing it), costing200 MBduring Pass 2 (300 MBtotal). - On modern server/desktop hardware with
20–40 GB/ssingle-core DRAM bandwidth:
200 MB / 40 GB/s = 5 ms 300 MB / 20 GB/s = 15 msSo
5–15 msis the physical speed-of-light floor set by memory bandwidth.3. Realistic CPU runtime:
- Compiled C / C++ / Rust: Pass 2 compiles to 10
memsetcalls and runs near the5–10 msbandwidth floor. Naive Pass 1 (counts[digits[i]]++) is often CPU-latency bound at~40–130 msbecause of a store-to-load forwarding dependency: when consecutive digits are equal (such as a run of0s), each increment must wait~4clock cycles (~1.3 nsat 3 GHz) for the previous store to the same counter to finish! Unrolling into 4 independent counter arrayscounts0..counts3breaks that dependency chain and brings total C runtime down to~10–25 ms. - Pure CPython: Bytecode loop dispatch costs roughly
20–50 nsper element per pass, so pure Python takes~4–10 secondsfor10^8digits (callingdigits.count(d)in C ford in range(10)drops CPython under~0.5 s).
- Pass 1 reads
Complete solution
from typing import List def sort_digits(digits: bytearray) -> None: """Sort `digits` (values 0..9) in place using two-pass counting sort.""" # counts[d]: frequency of digit d (0..9), e.g. [1, 3, 0, 0, 0, 2, 0, 1, 1, 0]. # Fixed length 10 guarantees O(1) auxiliary memory regardless of len(digits). counts: List[int] = [0] * 10 # Pass 1: scan the bytearray once to tally how many times each digit occurs. for value in digits: counts[value] += 1 # Pass 2: overwrite `digits` from left to right in ascending digit order 0..9. # Safe to overwrite in place because Pass 1 already captured all frequencies, # and we write byte-by-byte to avoid allocating any O(N) temporary slice buffer. write_pos = 0 for digit in range(10): frequency = counts[digit] for _ in range(frequency): digits[write_pos] = digit write_pos += 1✅ Submit now — all tests should pass.
Intuition & how it works
Imagine someone hands you a row of 100 million numbered tiles where every tile is stamped with a single digit from 0 to 9, and asks you to put them in order. Instead of comparing tiles two at a time and swapping them back and forth, you can grab a sticky note with 10 boxes labeled 0 through 9, walk down the row once making tally marks, and then walk back from the start laying down all the 0s, then all the 1s, and so on up to 9. Because two 4 tiles carry no other information and look identical, the 10 tallies tell you the exact sorted row!
A general comparison sort like digits[:] = sorted(digits) misses that shortcut completely. Comparing elements pairwise requires O(N log N) work — roughly 2.7 billion comparisons for 10^8 digits — and in Python sorted(digits) also allocates a temporary list of 10^8 8-byte pointers (~800 MB of extra RAM) just to sort 100 MB of data. Counting sort does one sequential read pass and one sequential write pass using just 10 integers of extra memory.
Here is a miniature 5-element trace on Example 2, digits = bytearray([9, 3, 9, 3, 3]):
- Count pass: Scan
[9, 3, 9, 3, 3]once to buildcounts = [0, 0, 0, 3, 0, 0, 0, 0, 0, 2](3appears three times,9appears twice, and all other buckets stay0). - Overwrite pass: Starting at
write_pos = 0, skip empty buckets0..2, write three3s, skip4..8, and write two9s directly intodigits. - Result:
digitsbecomesbytearray([3, 3, 3, 9, 9])in place, using only 10 counters.
Complexity
- Time:
O(N + K)=O(N), whereN = len(digits)andK = 10is the fixed alphabet size. Pass 1 reads each of theNbytes once, and the outerrange(10)loop in Pass 2 executes its inner bodycounts[0] + ... + counts[9] = Ntimes in total (200–300 MBof sequential DRAM traffic forN = 10^8, or~10–25 msin tuned C vs.~4–10 sin pure CPython). - Space:
O(K)=O(1)auxiliary memory. Regardless of whetherNis10or10^9, we only allocate the 10-elementcountslist and a few loop scalars (write_pos,digit,frequency), modifyingdigitsdirectly in place.
Edge cases
- Empty or single-element input (
N <= 1): Pass 1 counts zero or one byte, Pass 2 writes zero or one byte back to index0, anddigitsstays valid without special-case branches. - All
10^8digits identical (e.g., all0s or all9s): One counter reachesNwhile the other nine stay0. Byte-by-byte overwriting still usesO(1)memory, whereas slice-repeat tricks likebytes([digit]) * frequencywould blow up toO(N)extra RAM on this exact case. - Missing digits: Any digit with
counts[digit] == 0runs its innerrange(0)loop zero times and advanceswrite_posby0. - Huge
Nup to10^9:10^9bytes (1 GB) can have a single counter reach1,000,000,000. Pythonints never overflow; in C/C++/Rust, useuint64_tcounters (80bytes total) so even multi-billion-element arrays cannot overflow a 32-bitint.
Common mistakes
- Hidden
O(N)temporary allocations: Writingdigits[:] = sorted(digits)ordigits[pos:pos + c] = bytes([digit]) * callocates a buffer proportional toN, violating theO(1)extra-space constraint. Evennumpy.bincounton auint8array converts the input to 64-bit integers under the hood (8xmemory spike!). - Rebinding the local variable instead of mutating in place: Writing
digits = bytearray(...)insidesort_digitsonly points the local namedigitsat a new object, leaving the caller'sbytearraycompletely unsorted. - Building a full prefix-sum output buffer: Textbook counting sort allocates a second array of length
Nso equal keys preserve their original relative order (stability). Bare digits have no satellite data, so stability has no meaning here and wastes100 MB. - Overwriting before Pass 1 completes: Trying to write sorted digits into
digitswhile still scanningdigitsclobbers uncounted elements. - Ignoring memory bandwidth and pipeline hazards when estimating speed: At one operation per byte, wall-clock speed is controlled by DRAM bandwidth (how fast bytes move between RAM and CPU,
~5–15 msfloor for200–300 MBat20–40 GB/s) and store-to-load forwarding latency (consecutive increments of the same counter slot stalling for~4CPU cycles), not Big-O operation count alone.
Alternative approaches
- C-accelerated counting in Python (
bytearray.count+ fixed chunk writes): Callingdigits.count(d)ford in range(10)scansdigits10 times in optimized C (stillO(N)since10is constant, and~10xfaster in CPython than a Pythonforloop), and writing back in fixed64 KiBslices (block = bytes([d]) * 65536) keeps auxiliary memory strictlyO(1).
python
counts = [digits.count(d) for d in range(10)]
- Multi-table unrolled counting (systems C/Rust optimization): Maintain 4 independent counter arrays
c0[10], c1[10], c2[10], c3[10]updated ati, i+1, i+2, i+3in each loop step, then sum them at the end. Breaking the serial dependency on a single counter lets out-of-order CPU execution hit DRAM bandwidth speed even on long runs of identical digits, followed by 10memsetcalls. - Radix sort for wider integer ranges: When values span a huge range (such as 32-bit integers
0 .. 2^32 - 1),2^32counters would take16+ GB; radix sort applies counting sort one byte (256counters) at a time across 4 passes, though multi-byte radix passes requireO(N)scratch space to permute full integers cleanly.
Follow-up questions
-
If you store two decimal digits per byte using 4-bit nibbles, how do you sort them and what is the trade-off between CPU instructions and memory traffic? A nibble is a 4-bit half-byte (
0..15), which easily holds a digit0..9: pack even index2minto the upper 4 bits and odd index2m + 1into the lower 4 bits via(d_even << 4) | d_odd, cutting storage from100 MBto50 MB(store true lengthNseparately so an odd last digit isn't confused with a0nibble). To count fast without doubling loop iterations, tally a256-entry lookup histogrambyte_counts[b]over raw bytes first, then foldbyte_counts[b]into bothcounts[b >> 4]andcounts[b & 0x0F]in just 256 steps, and rewrite full bytes with(d << 4) | d(plus at most 9 boundary bytes where one digit run ends mid-byte). Because DRAM traffic drops in half (~100–150 MBtotal), a memory-bound C implementation runs nearly2xfaster despite the tiny bit-manipulation overhead. -
How would you split the work across multiple threads on a multicore machine without mutexes or atomic contention on the bucket counts? Split
digitsintoPcontiguous slices (one per thread) and give each thread its own thread-localcounts_p[10]array, padded to its own 64-byte cache line so threads never suffer false sharing (two cores fighting over ownership of the same 64-byte cache line when modifying adjacent variables). After all threads finish Pass 1 at a single synchronization barrier, sum thePtiny tables (10 * Padditions) to compute the exact output index interval[start_d, end_d)for each digit0..9, then divide[0, N)intoPnon-overlapping output ranges so each threadmemsets its own range with zero locks or atomic instructions. Speedup scales linearly with cores until aggregate memory traffic saturates all DRAM channels (typically 4–8 cores on a desktop/server socket). -
What changes in both algorithm structure and bottleneck analysis when the digits arrive as a disk or network stream instead of sitting in RAM? Now I/O throughput — such as
~125 MB/sover1 GbpsEthernet (~0.8 sfor100 MB) or~3–7 GB/sfrom an NVMe SSD (~15–35 ms) — becomes the bottleneck instead of DRAM. Read the stream in fixed-size chunks (e.g.,1 MiBbuffers) and use double buffering (overlapping the next asynchronous disk/network read with CPU counting on the previous chunk) soO(1)RAM (~2 MiB+ 10 counters) handles streams of arbitrary terabyte scale. Better yet, because the sorted output is completely described bycounts[0..9], you can emit the sorted stream lazily on the fly (or transmit the 80-byte run-length encoded counts directly!) without ever storing theNdigits in memory at once; if sorting a disk file in place, seek back to offset0after EOF and sequentially stream out each digit's run.
Follow-up questions
- If you store two decimal digits per byte using 4-bit nibbles, how do you sort them and what is the trade-off between CPU instructions and memory traffic?
- How would you split the work across multiple threads on a multicore machine without mutexes or atomic contention on the bucket counts?
- What changes in both algorithm structure and bottleneck analysis when the digits arrive as a disk or network stream instead of sitting in RAM?
Similar questions
- Audit and Harden Production Shell Snippets
- Fisher-Yates Uniformity Proof and Pitfalls
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging