I’d like to know if there’s some faster way to sort such array than quicksort/mergesort.
Maximum array’s length is 10^6.
Word’s length is >=10 and <= 100 and the word can contain a-z and spaces (27 different characters in total).
Characters are not unique in the words (they can repeat).
All the words in an array are equally long.
You can put all the words in a trie (or a radix tree), and then print it in a DFS order, starting from the “smaller” lexicographical letter at each level in the DFS.
This solution will be
O(n* |S|)where|S|is the average string length.Simple example:
Let the set of strings be
[ac,ab,aca]:The resulting trie will be:
And a DFS (which prefers lexicographically smaller characters): The DFS will start from
a, go tob, and then to the end sign ($) and will first printab, then go back toa, and right toc, and to the next$sign, and will printac, and next toaand its$and will printaca, resulting in printing:As expexted.