Group Anagrams
Problem
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> mp;
vector<vector<string>> ans;
for (int i = 0; i < strs.size(); i++) {
string s = strs[i];
sort(s.begin(), s.end());
mp[s].push_back(strs[i]);
}
for (auto i : mp) {
ans.push_back(i.second);
}
return ans;
}
};