How can I design an algorithm to sort n strings in O(dn) where d is the #of characters in a longest string?
1 Answer
You can use a trie.
Create an empty trie.
Loop over all strings, and place them in it.
Iterate over all the trie's values in order, and output them (see Trie complexity and searching as suggested below by Jean-Baptiste Yunès).
The complexity of 1 is constant. The complexity of each of 2 and 3 is O(dn).
4 Comments
Saurav Sahu
3rd point is not clear. How are you making sure the strings are sorted
Ami Tavory
@SauravSahu It's a pretty simple recursive function (see here an implementation). Starting at the node, recursively visit all children in order, while keeping track of current prefix. When you hit a leaf, output the total string along the path.
Jean-Baptiste Yunès
Complement: stackoverflow.com/questions/13032116/…
Ami Tavory
@Jean-BaptisteYunès Thanks for the useful link! Added inline