Given a set of strings, print all pairs of anagrams together. Two strings, X and Y, are called anagrams if we can get a string Y by rearranging the letters of the string X and using all the characters of the string X exactly once.

For example, the following word pairs are anagrams since we can rearrange the first string to get the second string and vice-versa. The problem requires the anagrams to be grouped.

 (actors, costar)
 (altered, related)
 (auctioned, education)
 (aspired, despair)
 (mastering, streaming)

Practice this problem

In the previous post, we have discussed a solution using a hash table. In this post, we will cover the Trie-based solution. The idea is simple – construct an empty Trie and do the following for each word:

  • Sort characters of the current word.
  • Insert the sorted word into our Trie.
  • Store the current unsorted word in the leaf node of the sorted word tree so that all anagrams will end up at the same leaf node.

Finally, traverse the Trie in a preorder fashion and print all anagrams together. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

auctioned education
actors costar
altered related
aspired despair
streaming mastering

Java


Download  Run Code

Output:

auctioned education
actors costar
altered related
aspired despair
streaming mastering

Python


Download  Run Code

Output:

[‘auctioned’, ‘education’]
[‘actors’, ‘costar’]
[‘altered’, ‘related’]
[‘aspired’, ‘despair’]
[‘streaming’, ‘mastering’]

The time complexity of the above solution is O(N × M × log(M)), where N is the total number of words and M is the maximum word length.