Radix Sort for Strings
Radix Sort for strings extends the classic digit-based Radix Sort idea to characters. Instead of processing numeric digits from least significant to most significant, the algorithm processes string characters, usually from the last character to the first (LSD - Least Significant Digit approach) or from the first to the last (MSD - Most Significant Digit approach).
How It Works
Each string is treated as a sequence of characters. Strings are padded to equal length using a placeholder character that sorts before all valid characters. The algorithm performs a stable counting sort pass on each character position, working right to left for LSD radix sort.
Algorithm Steps (LSD Radix Sort)
- Find the length of the longest string, pad shorter strings.
- Starting from the last character position, perform a stable counting sort on that position across all strings.
- Move to the previous character position and repeat.
- After processing the first character position, the strings are fully sorted.
def radix_sort_strings(arr):
max_len = max(len(s) for s in arr)
arr = [s.ljust(max_len, chr(0)) for s in arr]
for pos in range(max_len - 1, -1, -1):
buckets = [[] for _ in range(257)]
for s in arr:
buckets[ord(s[pos])].append(s)
arr = [s for bucket in buckets for s in bucket]
return [s.rstrip(chr(0)) for s in arr]
Complexity
| Case | Time | Space |
|---|---|---|
| Best/Average/Worst | O(n * k) | O(n + k) |
Here n is the number of strings and k is the maximum string length. Because Radix Sort avoids character-by-character comparisons across the whole string at once, it can outperform comparison-based sorts like Quick Sort for large collections of fixed or bounded-length strings.
Applications
- Sorting large dictionaries or word lists.
- Sorting fixed-length identifiers such as postal codes or product SKUs.
- Used internally in suffix array construction for string processing.
Watching LSD Radix Sort Work
Sort ["bat", "ab", "cab", "ba"]. The longest string has 3 characters, so the shorter ones are padded with the null character, shown here as an underscore: bat, ab_, cab, ba_. Since the null character sorts before every letter, padded strings come first wherever they tie.
| Pass | Position sorted on | Result after pass |
|---|---|---|
| 1 | Third character | ab_, ba_, cab, bat |
| 2 | Second character | ba_, cab, bat, ab_ |
| 3 | First character | ab_, ba_, bat, cab |
After removing padding the output is ab, ba, bat, cab. Look closely at pass 3: "ba_" and "bat" both start with b, and they stay in the order pass 2 left them. That is stability doing its job. If the bucket step reordered equal keys, the work of earlier passes would be lost and the result would be wrong.
MSD Radix Sort: Starting From the Left
The MSD version groups strings by their first character, then recursively sorts each group by the next character. It does not need padding, and it can stop early on groups that contain only one string.
def msd_sort(strings, pos=0):
if len(strings) <= 1:
return strings
finished = [s for s in strings if len(s) == pos] # shorter strings first
buckets = {}
for s in strings:
if len(s) > pos:
buckets.setdefault(s[pos], []).append(s)
result = finished
for ch in sorted(buckets):
result += msd_sort(buckets[ch], pos + 1)
return result
print(msd_sort(["bat", "ab", "cab", "ba", "b"]))
# ['ab', 'b', 'ba', 'bat', 'cab']
Using a dictionary keyed by character also means the code handles any Unicode character, unlike a fixed array of 257 buckets.
LSD or MSD?
| Aspect | LSD | MSD |
|---|---|---|
| Processing direction | Last character to first | First character to last |
| Best for | Fixed-length keys like codes or IDs | Variable-length strings such as words |
| Passes | Always one per character position | Can stop once a group is separated |
| Implementation | Simple loop | Recursive, more bookkeeping |
Practical Cautions
- Character range. The fixed-bucket version above indexes with
ord(), so any character beyond code 256, such as a Hindi letter or an emoji, raises an IndexError. Either widen the buckets or use a dictionary. - Case and locale. Sorting by raw character codes puts all uppercase letters before lowercase ones, so "Zebra" comes before "apple". Normalise case first if users expect dictionary order.
- Padding cost. One very long string forces LSD to pad every other string to its length, which wastes time and memory. MSD avoids that.
- Library sorts are often enough. For everyday code, Python's built-in
sorted()is highly optimised and simpler to maintain. Radix sort earns its place with very large sets of short or fixed-length keys.