Print Anagrams Together | Practice | GeeksforGeeks

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.
Note: The final output will be in lexicographic order.

Example 1:
Input:
N = 5
words[] = {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.

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. 

Your Task:
The task is to complete the function Anagrams() that takes a list of strings as input and returns a list of groups such that each group consists of all the strings that are anagrams.

Expected Time Complexity: O(N*|S|*log|S|), where |S| is the length of the strings.
Expected Auxiliary Space: O(N*|S|), where |S| is the length of the strings.

Constraints:
1<=N<=100
1<=|S|<=10
0
bsandeept717 hours ago
C++ Easy understand Code
class Solution{ public:   vector<vector<string> > Anagrams(vector<string>& string_list) {            unordered_map<int,string>mp;       for(int i=0;i<string_list.size();i++ )       {           string str=string_list[i];                      sort(str.begin(),str.end());           mp[i]=str;       }       vector<vector<string>>ans;       for(int j=0;j<string_list.size();j++)       {           if(mp[j]!="")           {          string str=mp[j];          vector<string>t;                  for(int i=0;i<mp.size();i++)          {              string temp=mp[i];              if(temp==str)              {                  t.push_back(string_list[i]);                  mp[i]="";              }          }          ans.push_back(t);       }      }       return ans;   }};
 
//some improvment also can be done
0
varunt2982 days ago
C++ solution
class Solution{
  public:
	vector<vector<string> > Anagrams(vector<string>& string_list) {
		map<map<char,int>, vector<string>> bmap;

		for (string str : string_list)
		{
			map<char,int> fmap;
			for (int i = 0; i < str.length(); i++)
			{
				fmap[str[i]]++;
			}


			auto it = bmap.find(fmap);

			if (it == bmap.end())
			{
				vector<string> list {str};
				//list.push_back(str);
				bmap.insert({fmap, list});
			}

			else
			{
				it->second.push_back(str);
				
			}

		}

		vector<vector<string>> anagrams;
		for (auto it = bmap.begin(); it != bmap.end(); it++)
			anagrams.push_back(it->second);

		return anagrams;

	}
};
0
akhilcool2 days ago
vector<vector<string> > Anagrams(vector<string>& string_list) {
      map<map<char,int>,vector<string>> m;
      vector<vector<string>> ans;
      int n=string_list.size();
     
      for(int i=0;i<n;i++){
          vector<string> container;
          map<char,int> temp;
          string carry=string_list[i];
          
          for(int j=0;j<n;j++)
            temp[carry[j]]++;
            
            if(m.find(temp)!=m.end()){	              			   m[temp].push_back(carry);
            }
            else{
        container.push_back(carry);
         m[temp]=container;
            }
          
          
      }
    
      for(auto it: m)
      ans.push_back(it.second);
      return ans;
    }
0
riamonga073 days ago
JAVA Solution | Using Trie | dfs(root)
[Upvote if you like the solution]
 
1 Building trie1.1 use a buffer array to sort each entry (GROUPING ANAGRAMS)1.2 store each entry as we usually do for a Trie1.3 make for LAST NODE:temp.isEnd = true;store respective string: temp.data.add(s);
 
2 DFS root (Thats how you dont use HashMap/HashSet !!!)2.1 dfs root.children2.2 add ends to ans list (Base Case)
 
Code
class TrieNode {
    List<String> data;
    TrieNode children[];
    boolean isEnd;

    TrieNode(){
        data = new ArrayList<>();
        children = new TrieNode[26];
        isEnd = false;
    }
}

class Solution {
    static TrieNode root;
    List<List<String>> ans;
    public List<List<String>> groupAnagrams(String[] strs) {
        ans = new ArrayList<>();
        
        root = new TrieNode();

        for(String word: strs){
            build(word);
        }
        
        dfs(root);
        
        return ans;
    }
    
    public void build(String s){
        TrieNode temp = root;
        char[] word = s.toCharArray();
        Arrays.sort(word);
        for(char c: word){
            TrieNode child = temp.children[c-'a'];
            if(child == null) temp.children[c-'a'] = new TrieNode();
            temp = temp.children[c-'a'];
        }
        temp.isEnd = true;
        temp.data.add(s);
    }
    
    public void dfs(TrieNode rt){
        if(rt.isEnd){
            ans.add(rt.data);
        }
        
        for(int i = 0; i < 26; i++){
            if(rt.children[i] != null) dfs(rt.children[i]);
        }
    }
}
+1
letitbesb1 week ago
(0.15/1.02) Frequency vector & Maps approach : 
vector<vector<string> > Anagrams(vector<string>& string_list) {
        //code here
        vector<vector<string> > ans;
        map<string,vector<int>> mp;
        map<vector<int>,string> mp2;
        for(string s:string_list){
            vector<int> temp(256,0);
            for(char c:s) temp[c]++; 
            mp[s]=temp; 
            if(mp2[temp].length()==0) mp2[temp]=s;
            else mp2[temp]+="_"+s;
        }
        for(auto it:mp2){
            regex regex("\\_");
            vector<string> out(
                    sregex_token_iterator(it.second.begin(), it.second.end(), regex, -1),
                    sregex_token_iterator()
                    );
            ans.push_back(out);
        }
        return ans;
    }
 
+1
sgupta0781 week ago
Sorted strings of all anagrams are same. So using sorted string as key and original string as value. Required is to print in lexicographic order so use ordered_map instead of unordered_map.
 
class Solution{
  public:
    vector<vector<string> > Anagrams(vector<string>& string_list) {
        //code here
        int sz=string_list.size();
        
        map<string, vector<string>> mp;
        
        for(int i=0;i<sz;i++){
            string s=string_list[i];
            sort(s.begin(), s.end());
            mp[s].push_back(string_list[i]);
        }
        vector<vector<string>> ans;
        for(auto it:mp){
            ans.push_back(it.second);
        }
        return ans;
    }
};
 
0
rm8420731 week ago
vector<vector<string>> Anagrams(vector<string>& a) {
        map<string,vector<string>> mp;
        vector<vector<string>> ans;
        
        if(a.size() == 0) return ans;
        
        for(int i=0;i<a.size();i++){
            string t = a[i];
            sort(t.begin(), t.end());
            mp[t].push_back(a[i]);
        }
        
        for(auto x : mp){
            vector<string> temp;
            for(auto y : x.second) temp.push_back(y);
            ans.push_back(temp);
        }
        
        return ans;
    }
+1
aditiyasharma1 week ago
class Solution{ public:   vector<vector<string> > Anagrams(vector<string>& string_list) {       //code here       vector<vector<string>>ans;       unordered_map<string,vector<string>>m;       for(int i=0;i<string_list.size();i++)       {           string s=string_list[i];           sort(s.begin(),s.end());           m[s].emplace_back(string_list[i]);       }       for(auto &i:m)           ans.emplace_back(i.second);       return ans;   }}; 
+1
avinashdhn19042 weeks ago
//C++ Fast solution Using trie datastructure

struct node{
  node *child[26];

  bool isend;
  node(){
      for(int i=0;i<26;i++)child[i]=NULL;
    
      isend=false;
  }
};

void insert(node *root,string &s,int in,unordered_map<node*,vector<int>>&mp){
    int n=s.length();
    for(int i=0;i<n;i++){
        if(root->child[s[i]-'a'])root=root->child[s[i]-'a'];
        else{
            root->child[s[i]-'a']= new node();
            root=root->child[s[i]-'a'];
        }
    }
    root->isend=true;
    mp[root].push_back(in);
}
class Solution{
  public:
    vector<vector<string> > Anagrams(vector<string>& string_list) {
       node *root= new node();
       unordered_map<node*,vector<int>>mp;
       for(int i=0;i<string_list.size();i++){
           string temp=string_list[i];
           sort(temp.begin(),temp.end());
           insert(root,temp,i,mp);
       }
       int n=mp.size();
       vector<vector<string>>ans;
       int i=0;
           vector<string>temp;
       for(auto it:mp){
           temp.clear();
           for(auto to:it.second)temp.push_back(string_list[to]);
           ans.push_back(temp);
       }
       return ans;
    }
};
0
divakarkumar20002 weeks ago
//c++
 vector<vector<string> > Anagrams(vector<string>& string_list) {
        unordered_map<string,vector<string>>umap;
        int n= string_list.size();
        vector<vector<string>>v;
        for(int i=0;i<n;i++)
        {
            string skey=string_list[i];
            sort(string_list[i].begin(),string_list[i].end());
            umap[string_list[i]].push_back(skey);
        }
        for(auto i : umap)
        {
            v.push_back(i.second);
        }
        return v;
    }
    
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.