#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

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

CaseTimeSpace
Best/Average/WorstO(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.

PassPosition sorted onResult after pass
1Third characterab_, ba_, cab, bat
2Second characterba_, cab, bat, ab_
3First characterab_, 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?

AspectLSDMSD
Processing directionLast character to firstFirst character to last
Best forFixed-length keys like codes or IDsVariable-length strings such as words
PassesAlways one per character positionCan stop once a group is separated
ImplementationSimple loopRecursive, 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.