Skip to problem
←

Radix Sort

Medium 0 attempts

Given an array arr of non-negative integers, return its values sorted in nondecreasing numeric order using radix sort. Preserve every occurrence of repeated values. You may return a new array or reorder the input.

Process decimal digits from least significant to most significant. Each digit pass must be stable: numbers with equal digits retain their order from the preceding pass. Treat missing higher digits as zero, and continue until the largest number's digits have been processed.

For [21, 12, 11], the ones-digit pass gives [21, 11, 12]; the tens-digit pass then gives [11, 12, 21]. Keeping 11 before 12 during the second pass preserves the ordering already established by the ones digit.

Zero is a valid value. Return the sorted array rather than printing it; the exercise asks for radix sort rather than a comparison-sort call.

Function contract

Implement radixSort(arr).

Output: Return all input values sorted in nondecreasing numeric order, preserving duplicates.

Example 1

Input
arr = [170,45,75,90,802,24,2,66]
Output
[2,24,45,66,75,90,170,802]

Example 2

Input
arr = [0,0]
Output
[0,0]
Constraints
  • 1 <= arr.length <= 10^5
  • 0 <= arr[i] <= 10^9

Least-Significant-Digit Radix Sort

Find the largest value with a loop. This avoids passing an entire large array as arguments to Math.max.

For each decimal position, distribute numbers into ten buckets using floor(number / exp) % 10. Visit the current array in order and append to each bucket, then concatenate buckets from digit zero to nine. This makes each pass stable.

After processing a digit, numbers are sorted by all digits processed so far. Stability preserves the lower-digit ordering within each equal higher-digit bucket. After the last digit of the maximum value, that ordering is the full numeric ordering. An all-zero array is already sorted and needs no digit passes.

javascript
function radixSort(arr) {
  let max = 0;
  for (const value of arr) max = Math.max(max, value);
  for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
    const buckets = Array.from({ length: 10 }, () => []);
    for (const n of arr) buckets[Math.floor(n / exp) % 10].push(n);
    arr = buckets.flat();
  }
  return arr;
}

Time: O(n + d × (n + 10)) | Space: O(n + 10), where d is the number of decimal digit passes (at most 10 under these bounds). The initial maximum scan also runs when all values are zero.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript