Print Anagrams Together

Given an array of strings, return all groups of strings that are anagrams. The groups must be created in order of their appearance in the original array. Look at the sample case for clarification. 


Input:

N = 5

words[] = {act,god,cat,dog,tac}

Output: 

god dog

act cat tac

Explanation:

There are 2 groups of

anagrams "god", "dog" make group 1.

"act", "cat", "tac" make group 2.

Example 2:


Input:

N = 3

words[] = {no,on,is}

Output: 

no on

is

Explanation:

There are 2 groups of

anagrams "no", "on" make group 1.

"is" makes group 2. 


1. Sort each word separately and then compare it to others to find anagrams

2.Use hash map to compare words and store their relative order.


c++ implementation:

vector<vector<string> > Anagrams(vector<string>& a) 
{
    unordered_map<string,vector<string>>m;
    
    for(int i=0;i<a.size();i++)
    {
       string s=a[i];
       sort(s.begin(),s.end());
       m[s].push_back(a[i]);
    }
    
    vector<vector<string>>r;
    

    for(auto x:m)
    {
       r.push_back(x.second);
    }
    return r;
}






darkmode