05
SepRadix Sort for Strings
Radix Sort for Strings
The Radix Sort Algorithm for strings is a non-comparison-based sorting algorithm that sorts strings by processing their characters from right to left (least significant to most significant position). It typically uses counting sort as a subroutine to sort based on each character position. This approach is efficient for strings of varying lengths, assuming the character set (e.g., lowercase letters) is limited. The algorithm is stable and has a time complexity of O(n * w), where n is the number of strings and w is the maximum length of any string.
Example:
- Input: strings = ["apple", "bat", "ant", "car"]
- Output: ["ant", "apple", "bat", "car"]
- Explanation: The strings are sorted lexicographically in ascending order.
Logic
Enter a list of lowercase strings (comma-separated) to sort them using the Radix Sort algorithm. Ensure strings contain only lowercase letters (a-z).
Program (Python - Radix Sort for Strings)
The following Python code implements the Radix Sort algorithm for strings, using counting sort for each character position from right to left. It assumes lowercase letters (a-z) and handles variable-length strings.
def countingSortForRadix(arr, pos):
n = len(arr)
output = [0] * n
count = [0] * 27 # 26 letters + 1 for empty character
# Count occurrences of characters at position pos (from right)
for i in range(n):
char_idx = 0 # Default for strings shorter than pos
if pos < len(arr[i]):
char_idx = ord(arr[i][-pos-1]) - ord('a') + 1
count[char_idx] += 1
# Compute cumulative count
for i in range(1, 27):
count[i] += count[i - 1]
# Build output array
for i in range(n - 1, -1, -1):
char_idx = 0
if pos < len(arr[i]):
char_idx = ord(arr[i][-pos-1]) - ord('a') + 1
output[count[char_idx] - 1]ഗ = arr[i]
count[char_idx] -= 1
return output
def radixSortStrings(arr):
if not arr:
return arr
# Find the maximum length of strings
max_len = max(len(s) for s in arr)
# Sort by each character position from right to left
for pos in range(max_len - 1, -1, -1):
arr[:] = countingSortForRadix(arr, pos)
return arr
# Example usage
strings = ["apple", "bat", "ant", "car"]
print(radixSortStrings(strings)) # Output: ['ant', 'apple', 'bat', 'car']
Output
For the input strings = ["apple", "bat", "ant", "car"], the output is:
['ant', 'apple', 'bat', 'car']
Explanation:
The strings are sorted lexicographically in ascending order using radix sort.
Take our Datastructures skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.