Radix and Counting Sort - aloalgo.com

Radix and Counting Sort

These are non-comparison sorts that achieve O(n) time by exploiting properties of the input (integer values, fixed range). They bypass the O(n log n) lower bound of comparison-based sorting.

Counting Sort

Idea: Count occurrences of each value, then use the counts to place elements in sorted order. Works when values are integers in a known range [0, k].
  • Time: O(n + k) where k is the range of values
  • Space: O(n + k)
  • Stable: Yes (with proper implementation)
  • Limitation: Only works for integers with limited range

Stable Counting Sort

For stability (preserving relative order of equal elements), use prefix sums to determine positions:

Radix Sort

Idea: Sort integers digit by digit, from least significant to most significant (LSD) or vice versa (MSD). Uses a stable sort (usually counting sort) for each digit.
  • Time: O(d * n) where d is the number of digits
  • Space: O(n + k) where k is the radix (base, usually 10)
  • Stable: Yes
  • Best for: Fixed-length integers, strings of same length

Comparison

AlgorithmTimeSpaceStableUse Case
Counting SortO(n + k)O(n + k)YesSmall range integers
Radix SortO(d * n)O(n + k)YesFixed-length integers/strings

When to Use

SituationBest ChoiceWhy
Integers in range [0, k]Counting SortO(n + k), simple
Large integers, small digitsRadix SortO(d * n), handles big numbers
Fixed-length stringsRadix SortSort character by character
Range k > n log nComparison SortO(n log n) beats O(n + k)

Interview Tips

  • Know the constraints: These only work for specific inputs (integers, limited range). Always clarify input constraints.
  • Counting sort as a building block: It's used inside radix sort and bucket sort.
  • When k is small: If told values are in range [0, 100], counting sort gives O(n).
  • Stability matters for radix: Radix sort requires a stable sub-sort to work correctly.
  • Compare to O(n log n): Only faster when k or d is smaller than log n.
Was this helpful?
© 2026 aloalgo.com. All rights reserved.