VOOZH about

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

⇱ Group Anagrams Together Using Sorting - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Group Anagrams Together Using Sorting

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.

Using Sorted Words as Keys

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 or dictionary with the sorted strings as keys and the index of the anagram group in the result array as the value.


Output
act cat tac 
god dog 

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

Related Article: Group Anagrams Together

Comment