Ordering a Hundred Million Decimal Digits in Place
Heaps, Sorting & SearchModel answerLast updated
Order a huge byte array holding only the values 0 to 9 in linear time with constant extra memory, then reason about storage layout, memory bandwidth and expected runtime.
Ordering a Hundred Million Decimal Digits in Place
A bytearray holds up to 10^8 elements, and every element is a decimal digit from 0 to 9. Your job is to reorder the array so the values are non-decreasing. The work must be done inside the array itself, in linear time, with only a fixed amount of extra memory.
def sort_digits(digits: bytearray) -> None:
"""Reorder `digits` in place so it is non-decreasing."""
Input and output
- Input: a
bytearraywhose elements all lie in[0, 9]. - Output: nothing is returned. The same array must hold the sorted values afterwards.
Constraints
- The nominal length is
10^8, but the routine should work for any length0 <= N <= 10^9. - Every element satisfies
0 <= digits[i] <= 9. - Extra space must be
O(1): a handful of counters, not a second copy of the data. - Running time must be
O(N). A comparison sort atO(N log N)is not what is wanted.
Example
data = bytearray([4, 2, 0, 9, 2, 4, 1])
sort_digits(data)
print(list(data)) # [0, 1, 2, 2, 4, 4, 9]
Edge cases to cover
- All elements identical, or some digits never occurring.
- Empty arrays and arrays with a single element.
What to discuss
- State the algorithm and justify its correctness and complexity.
- Compare storage layouts: 64-bit integers, 32-bit integers, one byte per digit, and two digits packed per byte.
- Explain what actually limits speed on real hardware, and give a realistic running-time estimate for
10^8digits. - Be ready for follow-ups: packing, multiple cores, and data that does not fit in memory.
Hints
Hint 1
With only ten distinct values and no attached payload, do you really need to compare elements, or is it enough to know how many times each value appears?
Hint 2
Once you have the ten frequencies, you can regenerate the sorted array by overwriting it from left to right. Do you need prefix sums or an output buffer for that?
Hint 3
The loop does almost no arithmetic per element. Count the bytes moved to and from memory for each storage layout, and ask whether the job is compute-bound or bandwidth-bound.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: counting sort with ten counters
Because the alphabet is just {0..9} and the elements carry no extra data, two equal digits are interchangeable. That means the original order does not matter, so I do not need stability, prefix sums, or an output array.
- Count: one pass over the array, incrementing
counts[digit]. - Rewrite: walk the array from the left and write
counts[0]zeros, thencounts[1]ones, and so on up to nine.
Why it is correct
- After step 1,
counts[d]is the number of occurrences ofd, and the counts sum toN. - Step 2 fills
[0, c0), then[c0, c0+c1), and so on. These ranges are disjoint and cover[0, N)exactly, so every slot is written once. - Values never decrease along the array, and each digit appears as often as in the input. A sorted rearrangement of the input is unique, so this is the answer.
Complexity
- Time:
O(N + k)withk = 10, soO(N): one read pass and one write pass. - Space:
O(k) = O(1). Use 64-bit counters; withNup to10^9a 32-bit unsigned counter would still fit, but 64-bit removes any doubt at no cost.
Code (Python)
A per-element Python loop over 10^8 items costs seconds of interpreter overhead, so push the work into C-level primitives.
def sort_digits(digits: bytearray) -> None:
n = len(digits)
if n <= 1:
return
counts = [digits.count(d) for d in range(10)]
if sum(counts) != n:
raise ValueError("input contains values outside 0..9")
CHUNK = 1 << 16 # fixed 64 KB write block
pos = 0
for d in range(10):
c = counts[d]
if c == 0:
continue
block = bytes((d,)) * min(c, CHUNK)
end = pos + c
while pos < end:
k = min(CHUNK, end - pos)
digits[pos:pos + k] = block[:k] # same-length slice write, in place
pos += k
Notes:
bytearray.countdoes ten C-level scans instead of one, which is stillO(N)and runs near memory speed.- Writing from a fixed 64 KB block avoids allocating a
bytesobject of up to 100 MB, so auxiliary memory stays constant. - The sum check catches out-of-range values instead of silently corrupting the array.
In C, C++ or Rust, the textbook version is simply:
for (i = 0; i < n; i++) counts[a[i]]++;
for (d = 0; d < 10; d++) { memset(a + pos, d, counts[d]); pos += counts[d]; }
Memory layout and runtime
The algorithm does almost no computation per element, so it is memory-bandwidth bound. Layout therefore matters more than the algorithm.
| Layout | Array size | Traffic (read + write) |
|---|---|---|
int64 per digit | 800 MB | about 1.6 GB |
int32 per digit | 400 MB | about 0.8 GB |
uint8 per digit | 100 MB | about 200 MB |
| two digits per byte | 50 MB | about 100 MB |
Using 64-bit integers is eight times more traffic than bytes for no benefit.
Estimate for the byte layout:
- 200 MB at 20-40 GB/s of DRAM bandwidth gives a floor of roughly 5-10 ms.
- One core typically sustains 10-20 GB/s, and ordinary stores cause write-allocate reads (the line is fetched before being overwritten), adding hidden traffic. Streaming stores, which
memsetoften uses for big sizes, avoid this. - A realistic single-thread C figure is about 15-40 ms. CPython using
countplus slice writes is around 0.1-0.5 s. A naive Python loop takes several seconds.
Micro-architectural trap: counts[a[i]]++ creates a store-to-load dependency whenever neighbouring digits are equal, and the all-identical input is the worst case. Using 4-8 separate count arrays indexed by i % 4 (summed at the end) breaks the dependency chain. SIMD byte compares plus popcount can reach full bandwidth.
Follow-ups
Packed nibbles. Store hi << 4 | lo. Footprint and traffic halve. For counting, use a 256-entry table indexed by the whole byte (it stays in L1), then fold each byte b into counts[b >> 4] and counts[b & 15]. For writing, a full byte inside a run is d * 0x11, which memset handles; only the boundary byte between two digits needs special treatment, and an odd N leaves one padding nibble. The extra ALU work is hidden behind memory latency, so expect close to a 2x gain.
Multiple cores. Split the array into P contiguous chunks, each thread with a private counts[10] padded to its own cache line to avoid false sharing. Then reduce the P histograms (O(10P)), compute global prefix sums to define the ten output ranges, split [0, N) evenly across threads, and let each thread memset the pieces it owns. No locks are needed. Scaling stops once the memory controllers saturate, typically at 4-8 cores.
Data that does not fit in memory or comes from disk or network. Count chunk by chunk with large sequential or double-buffered reads, keeping only 10 counters. The result can be represented as ten (digit, count) pairs and expanded only if a consumer needs the full sequence. The bottleneck becomes I/O: 100 MB at NVMe speeds of 3-7 GB/s takes tens of milliseconds, while a 1 Gbps link needs about 0.8 s.
Common mistakes
- Reaching for
sorted()or a general comparison sort, which isO(N log N)and allocates a lot. - Building a full output buffer or prefix sums when nothing needs stability.
- Allocating a
bytes([d]) * counttemporary that is itself 100 MB, breaking theO(1)space claim. - Storing digits as 64-bit integers and then being surprised by the bandwidth cost.
- Using 32-bit signed counters when lengths could approach the limit, or ignoring invalid values.
- Forgetting trivial cases: empty input, single element, one digit repeated everywhere.