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^8 bytes).
  • Every element satisfies 0 <= digits[i] <= 9.
  • digits must be mutated in place and sort_digits must return None.
  • Time complexity: O(N).
  • Auxiliary space complexity: O(1) (a fixed 10-counter table with no O(N) temporary slices or copies, even when all N bytes are identical).

Step-by-step walkthrough

  1. Understand the problem and the memory budget

    We are given a bytearray named digits of length N (with N = 100,000,000 in the scenario, and 0 <= N <= 10^9 in general), where every element is a single digit from 0 to 9 inclusive. We must sort digits in place in non-decreasing order and return None, using O(N) time and O(1) extra space.

    A Python bytearray is a mutable, contiguous array of raw bytes where each slot stores one integer in 0..255 using 1 byte of memory. That means 10^8 digits take 100,000,000 bytes (100 MB, or about 95.4 MiB), and iterating over digits yields plain Python int values one by one.

  2. 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 of N * log2(N) comparisons. At N = 10^8, log2(10^8) is about 26.6, so it performs roughly 2.7 * 10^9 comparisons even though only ten distinct values exist.
    • Too much memory (O(N) extra space): sorted(digits) builds a temporary Python list holding 10^8 8-byte object pointers — roughly 800 MB of extra RAM just to sort 100 MB of bytes!
  3. Key idea: ten frequency counters capture the entire sorted array

    Because every element is a bare integer in 0..9 with no attached metadata, two 4s are completely indistinguishable. That means the final sorted array depends only on how many times each digit 0..9 appears:

    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:

    1. Pass 1 (Count): Read digits from start to finish and increment counts[value] for each byte.
    2. Pass 2 (Overwrite): Walk digits from index 0 to N - 1, writing counts[0] zeros, counts[1] ones, ..., up to counts[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 counts sorts in place with O(1) extra memory.

  4. Phase 1: Count how often each digit appears

    Allocate a fixed list of 10 integer counters initialized to 0, then scan digits once:

    # 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
    

    On counter width in lower-level languages: N = 10^8 (and even N = 10^9) fits inside a signed 32-bit integer (max ~ 2.14 * 10^9), but using ten 64-bit unsigned integers (uint64_t[10], only 80 bytes total!) is the safest systems practice so larger inputs never overflow. Python ints have arbitrary precision and never overflow.

  5. Phase 2: Overwrite the bytearray in sorted order

    Once Pass 1 finishes, counts holds everything we need to know about the input, so we can safely overwrite digits in place from left to right using a cursor write_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 += 1
    

    Why write byte by byte instead of a slice assignment like digits[write_pos : write_pos + frequency] = bytes([digit]) * frequency? Because bytes([digit]) * frequency allocates a temporary bytes object of length frequency! If all 10^8 digits are 0, that temporary buffer takes 100 MB, silently breaking our O(1) space guarantee.

  6. 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              -> unchanged
    

    Because sum(counts) == 8, write_pos finishes at 8 == len(digits) and every slot is written once.

  7. 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 MB sequentially from DRAM (counts is only 80 bytes and stays pinned in L1 cache or CPU registers).
    • Pass 2 writes 100 MB sequentially. With streaming (non-temporal) stores (special instructions that write full cache lines straight to memory without reading old bytes first), Pass 2 costs 100 MB of DRAM traffic (200 MB total). 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), costing 200 MB during Pass 2 (300 MB total).
    • On modern server/desktop hardware with 20–40 GB/s single-core DRAM bandwidth:
    200 MB / 40 GB/s = 5 ms       300 MB / 20 GB/s = 15 ms
    

    So 5–15 ms is the physical speed-of-light floor set by memory bandwidth.

    3. Realistic CPU runtime:

    • Compiled C / C++ / Rust: Pass 2 compiles to 10 memset calls and runs near the 5–10 ms bandwidth floor. Naive Pass 1 (counts[digits[i]]++) is often CPU-latency bound at ~40–130 ms because of a store-to-load forwarding dependency: when consecutive digits are equal (such as a run of 0s), each increment must wait ~4 clock cycles (~1.3 ns at 3 GHz) for the previous store to the same counter to finish! Unrolling into 4 independent counter arrays counts0..counts3 breaks that dependency chain and brings total C runtime down to ~10–25 ms.
    • Pure CPython: Bytecode loop dispatch costs roughly 20–50 ns per element per pass, so pure Python takes ~4–10 seconds for 10^8 digits (calling digits.count(d) in C for d in range(10) drops CPython under ~0.5 s).
  8. 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]):

  1. Count pass: Scan [9, 3, 9, 3, 3] once to build counts = [0, 0, 0, 3, 0, 0, 0, 0, 0, 2] (3 appears three times, 9 appears twice, and all other buckets stay 0).
  2. Overwrite pass: Starting at write_pos = 0, skip empty buckets 0..2, write three 3s, skip 4..8, and write two 9s directly into digits.
  3. Result: digits becomes bytearray([3, 3, 3, 9, 9]) in place, using only 10 counters.

Complexity

  • Time: O(N + K) = O(N), where N = len(digits) and K = 10 is the fixed alphabet size. Pass 1 reads each of the N bytes once, and the outer range(10) loop in Pass 2 executes its inner body counts[0] + ... + counts[9] = N times in total (200–300 MB of sequential DRAM traffic for N = 10^8, or ~10–25 ms in tuned C vs. ~4–10 s in pure CPython).
  • Space: O(K) = O(1) auxiliary memory. Regardless of whether N is 10 or 10^9, we only allocate the 10-element counts list and a few loop scalars (write_pos, digit, frequency), modifying digits directly 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 index 0, and digits stays valid without special-case branches.
  • All 10^8 digits identical (e.g., all 0s or all 9s): One counter reaches N while the other nine stay 0. Byte-by-byte overwriting still uses O(1) memory, whereas slice-repeat tricks like bytes([digit]) * frequency would blow up to O(N) extra RAM on this exact case.
  • Missing digits: Any digit with counts[digit] == 0 runs its inner range(0) loop zero times and advances write_pos by 0.
  • Huge N up to 10^9: 10^9 bytes (1 GB) can have a single counter reach 1,000,000,000. Python ints never overflow; in C/C++/Rust, use uint64_t counters (80 bytes total) so even multi-billion-element arrays cannot overflow a 32-bit int.

Common mistakes

  • Hidden O(N) temporary allocations: Writing digits[:] = sorted(digits) or digits[pos:pos + c] = bytes([digit]) * c allocates a buffer proportional to N, violating the O(1) extra-space constraint. Even numpy.bincount on a uint8 array converts the input to 64-bit integers under the hood (8x memory spike!).
  • Rebinding the local variable instead of mutating in place: Writing digits = bytearray(...) inside sort_digits only points the local name digits at a new object, leaving the caller's bytearray completely unsorted.
  • Building a full prefix-sum output buffer: Textbook counting sort allocates a second array of length N so equal keys preserve their original relative order (stability). Bare digits have no satellite data, so stability has no meaning here and wastes 100 MB.
  • Overwriting before Pass 1 completes: Trying to write sorted digits into digits while still scanning digits clobbers 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 ms floor for 200–300 MB at 20–40 GB/s) and store-to-load forwarding latency (consecutive increments of the same counter slot stalling for ~4 CPU cycles), not Big-O operation count alone.

Alternative approaches

  • C-accelerated counting in Python (bytearray.count + fixed chunk writes): Calling digits.count(d) for d in range(10) scans digits 10 times in optimized C (still O(N) since 10 is constant, and ~10x faster in CPython than a Python for loop), and writing back in fixed 64 KiB slices (block = bytes([d]) * 65536) keeps auxiliary memory strictly O(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 at i, i+1, i+2, i+3 in 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 10 memset calls.
  • Radix sort for wider integer ranges: When values span a huge range (such as 32-bit integers 0 .. 2^32 - 1), 2^32 counters would take 16+ GB; radix sort applies counting sort one byte (256 counters) at a time across 4 passes, though multi-byte radix passes require O(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 digit 0..9: pack even index 2m into the upper 4 bits and odd index 2m + 1 into the lower 4 bits via (d_even << 4) | d_odd, cutting storage from 100 MB to 50 MB (store true length N separately so an odd last digit isn't confused with a 0 nibble). To count fast without doubling loop iterations, tally a 256-entry lookup histogram byte_counts[b] over raw bytes first, then fold byte_counts[b] into both counts[b >> 4] and counts[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 MB total), a memory-bound C implementation runs nearly 2x faster 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 digits into P contiguous slices (one per thread) and give each thread its own thread-local counts_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 the P tiny tables (10 * P additions) to compute the exact output index interval [start_d, end_d) for each digit 0..9, then divide [0, N) into P non-overlapping output ranges so each thread memsets 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/s over 1 Gbps Ethernet (~0.8 s for 100 MB) or ~3–7 GB/s from an NVMe SSD (~15–35 ms) — becomes the bottleneck instead of DRAM. Read the stream in fixed-size chunks (e.g., 1 MiB buffers) and use double buffering (overlapping the next asynchronous disk/network read with CPU counting on the previous chunk) so O(1) RAM (~2 MiB + 10 counters) handles streams of arbitrary terabyte scale. Better yet, because the sorted output is completely described by counts[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 the N digits in memory at once; if sorting a disk file in place, seek back to offset 0 after EOF and sequentially stream out each digit's run.

Follow-up questions

Similar questions

More Modal interview questions

All 3 Modal questions →