# Sorting strings using Counting Sort in O(n), where n is the total number of characters in all the strings

Suppose, you are given an array of strings of different lengths, but the total number of characters over all the strings is n. Describe an algorithm using Counting Sort to sort the strings in alphabetic order (eg. algorithm < cs < hello) in O(n) time.

• What are your thoughts on the question? – Yuval Filmus Feb 6 at 1:46
• The common assessment of the time required by Counting Sort has a second parameter in addition to some measure $n$ of the input. Please show how far you got. – greybeard Feb 6 at 5:37

Here is the general idea:

1. Sort all the strings according to their first character (refer to each string using an index to save time).

2. Partition the strings according to their first character, and run recursively on each part (deleting in your mind the first character).

I'll let you work out the details.

• I am thinking the same. But will it be still in O(n) ? – Hasan Shahriar Feb 6 at 1:58
• I think so. The complexity of the zeroth level of the recursion tree is the number of first characters. The complexity of the first level of the recursion tree is the number of second characters. And so on. – Yuval Filmus Feb 6 at 2:08
• Yes, it makes sense. Thank you. – Hasan Shahriar Feb 6 at 2:16
• The crux of Counting Sort is its dependence on "alphabet" size, say $S: |\Sigma|$. With "single letter strings", this should amount to $O(n+S)$, with two strings of length $n/2$, I see $O(nS)$ – greybeard Feb 6 at 6:05
• Alphabet is constant. – Yuval Filmus Feb 6 at 6:18