KatInterview

Ordering a Hundred Million Decimal Digits in Place

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchcounting-sortin-placememory-bandwidth

Last 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 bytearray whose 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 length 0 <= 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 at O(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

  1. State the algorithm and justify its correctness and complexity.
  2. Compare storage layouts: 64-bit integers, 32-bit integers, one byte per digit, and two digits packed per byte.
  3. Explain what actually limits speed on real hardware, and give a realistic running-time estimate for 10^8 digits.
  4. 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.