Lexicographic sorting: Given a set of strings, return them in lexicographic order (dictionary/alphabetical order).

Practice this problem

Lexicographic sorting of a set of keys can be accomplished with a simple Trie-based algorithm as follows:

  • Insert all keys into a Trie.
  • Print all keys in the Trie by performing preorder traversal on Trie to get output in lexicographically increasing order.

Following is the C++, Java, and Python implementation of the idea. Trie currently supports the lowercase English characters a – z. We can easily extend the solution to support all ASCII characters.

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
a
accomplished
algorithm
all
based
be
by
can
depth
first
in
increasing
insert
is
keys
kind
lexicographic
lexicographically
means
of
order
output
preorder
results
set
simple
sorting
that
the
traversal
trie
we
which
with

The time complexity of the above solution is O(N.M), where N is the total number of given words and M is the maximum word length. The auxiliary space required by the program is O(N × M).