I have an array of strings, each one with a different length. e.g:
s[0] = "sSWXk"
s[1] = "qCk"
s[2] = "sOQQXPbk"
.
.
.
s[x] = "KVfdQk";
I also am given that
n = s[0].length() + s[1].length() + ... + s[x].length()
I need a sorting algorithm with time complexity O(n) for sorting these strings lexicographically, so that (for example)
a < ab < b < bbc < c < ca
Any suggestions? The time complexity is the essential requirement in the algorithm.
There is a data structure called a trie that is optimally suited for this. If you insert all the words into the trie and then do a DFS over the trie, you will get the words back in sorted order. Doing so takes time O(n) as well, where n is the total number of characters in all the strings.
Since I assume that this is homework, I’ll leave the details of how to implement the trie as an exercise. 🙂
Hope this helps!