Group Anagrams
Medium · Arrays & hashing
Jump to codePartition a list of lowercase English words so each group contains words with identical letter counts. Return the groups and words in any order.
Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["ate","eat","tea"],["bat"],["nat","tan"]]
Example 2
strs = [""]
Output: [[""]]
Constraints
- 1 <= strs.length <= 1000.
- 0 <= strs[i].length <= 100
- strs[i] is made up of lowercase English letters.
Need a hint?
Find a signature that every rearrangement of a word shares.
Asked in real interviews
Candidates reported versions of Group Anagrams from these company interviews. Some company questions are locked and open with Premium or XP.
- Group anagrams and count string in gridJ.P. Morgan
- Group Anagrams Without Sorted Character SignaturesAmazon
- Group words into anagram listsBloomberg
Solution approach
Count the 26 letters in each word and use the resulting immutable tuple as a map key. Append the word to that key’s group. Unlike concatenating raw counts without separators, a tuple cannot confuse different frequency vectors. Return the map’s groups.
Complexity
O(total characters + 26n) time and O(total characters + 26n) space including output.
Python reference solution
def groupAnagrams(strs):
groups = {}
for word in strs:
counts = [0] * 26
for char in word:
counts[ord(char) - ord('a')] += 1
groups.setdefault(tuple(counts), []).append(word)
return list(groups.values())
JavaScript solution
function groupAnagrams(strs) {
const groups = new Map();
for (const word of strs) {
const counts = Array(26).fill(0);
for (const char of word) counts[char.charCodeAt(0) - 97]++;
const key = counts.join(',');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
}
Java solution
import java.util.*;
class Solution {
public String[][] groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for (String word : strs) {
int[] counts = new int[26];
for (char c : word.toCharArray()) counts[c - 'a']++;
String key = Arrays.toString(counts);
groups.computeIfAbsent(key, ignored -> new ArrayList<>()).add(word);
}
String[][] answer = new String[groups.size()][];
int i = 0;
for (List<String> group : groups.values()) answer[i++] = group.toArray(new String[0]);
return answer;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string> &strs) {
unordered_map<string, vector<string>> groups;
for (const string& word : strs) {
array<int, 26> counts{};
for (char c : word) counts[c - 'a']++;
string key;
for (int count : counts) key += to_string(count) + ",";
groups[key].push_back(word);
}
vector<vector<string>> answer;
for (auto& entry : groups) answer.push_back(move(entry.second));
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 10 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
"eat",
"tea",
"tan",
"ate",
"nat",
"bat"
]
][
[
"ate",
"eat",
"tea"
],
[
"bat"
],
[
"nat",
"tan"
]
][
[
""
]
][
[
""
]
][
[
"a"
]
][
[
"a"
]
][
[
"",
"b",
""
]
][
[
"",
""
],
[
"b"
]
][
[
"abc",
"bca",
"cab",
"xyz",
"zyx",
"a"
]
][
[
"a"
],
[
"abc",
"bca",
"cab"
],
[
"xyz",
"zyx"
]
]Drafts are saved per language in this browser when storage is available.