[AlgoExpert] Group Anagrams

Group Anagrams

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>

using namespace std;

vector<vector<string>> groupAnagrams(vector<string> words) {
unordered_map<string, vector<string>> mp;
for(auto& w : words) {
string s = w;
sort(begin(s), end(s));
mp[s].push_back(w);
}
vector<vector<string>> res;
for(auto& [_, g] : mp) res.push_back(g);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/group-anagrams/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.