0

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 1

1

You can use a trie.

  1. Create an empty trie.

  2. Loop over all strings, and place them in it.

  3. 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).

Sign up to request clarification or add additional context in comments.

4 Comments

3rd point is not clear. How are you making sure the strings are sorted
@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-BaptisteYunès Thanks for the useful link! Added inline

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.