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:
a
/ \
/ \
b c
| / \
$ $ a
|
$
And a DFS (which prefers lexicographically smaller characters): The DFS will start from a
, go to b
, and then to the end sign ($
) and will first print ab
, then go back to a
, and right to c
, and to the next $
sign, and will print ac
, and next to a
and its $
and will print aca
, resulting in printing:
ab
ac
aca
As expexted.