VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-a-sequence-of-words-print-all-anagrams-together/

⇱ Group Anagrams Together - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Group Anagrams Together

Last Updated : 23 Jul, 2025

Given an array of words arr[], the task is to groups strings that are anagrams. An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.

Example:

Input: arr[] = ["act", "god", "cat", "dog", "tac"]
Output: [["act", "cat", "tac"], ["god", "dog"]]
Explanation: There are 2 groups of anagrams "god", "dog" make group 1. "act", "cat", "tac" make group 2.

Input: arr[] = ["listen", "silent", "enlist", "abc", "cab", "bac", "rat", "tar", "art"]
Output: [["abc", "cab", "bac"], ["listen", "silent", "enlist"],["rat", "tar", "art"]]
Explanation:
Group 1: "abc", "bac" and "cab" are anagrams.
Group 2: "listen", "silent" and "enlist" are anagrams.
Group 3: "rat", "tar" and "art" are anagrams.

[Naive Approach] Using sorted words as keys - O(n*k*log(k)) Time and O(n*k) Space

The idea is that if we sort two strings which are anagrams of each other, then the sorted strings will always be the same. So, we can maintain a hash map with the sorted strings as keys and the index of the anagram group in the result array as the value.

To know more about the implementation, please refer to Group Anagrams Together Using Sorting.

[Expected Approach] Using Frequency as keys - O(n*k) Time and O(n*k) Space

The idea is to that if two strings are anagrams of each other, then the frequency of all characters in both strings will always be the same. So, we can maintain a hash map with the count of characters as keys and the index of the anagram group in the result array as the value. For each word, we can first construct a frequency array of size 26 to store the frequency of each character in the word. Then, we can append the frequency of each character separated by a delimiter, say '$' to form the key for hash map.

Note the MAX_CHAR is alphabet size of input characters which is typically a constant. If we have only lower case characters, then MAX_CHAR is 26 only. If we consider all ASCII characters, then MAX_CHAR is 256.


Output
act cat tac 
god dog 

Time Complexity: O(n*k), where is the number of words and k is the maximum length of a word.
Auxiliary Space: O(n*k)

Comment