49. Group Anagrams
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to group an array of strings into sub-arrays where each sub-array contains strings that are anagrams of each other. Anagrams are words formed by rearranging the letters of another word, which means they must contain the same characters with the same frequencies.
Solution
Group Anagrams in Python
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: list[str]) -> list[list[str]]:
# Use a defaultdict to automatically handle the creation of new lists for new keys.
# The key will be a tuple of character counts, which is hashable.
# The value will be a list of strings.
anagram_map = defaultdict(list)
for s in strs:
# Create a character count array of size 26 for 'a' through 'z'.
count = [0] * 26
for char in s:
count[ord(char) - ord('a')] += 1
# Convert the list of counts to a tuple so it can be used as a dictionary key.
# Lists are mutable and therefore cannot be dictionary keys.
# Tuples are immutable and hashable.
anagram_map[tuple(count)].append(s)
# The values of the dictionary are the grouped anagrams.
return list(anagram_map.values())
Group Anagrams in Java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Handle null or empty input
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
// Use a HashMap to group anagrams.
// The key is a string representation of the character counts.
// The value is the list of strings that are anagrams.
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
// Create a character count array (26 for 'a' through 'z').
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
// Convert the character count array to a string to be used as a key.
// A separator is crucial to distinguish counts, e.g., {1, 12} vs {11, 2}.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String key = sb.toString();
// If the key is not in the map, create a new list.
// Then add the current string to the list for this key.
map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
// The values of the map are the lists of grouped anagrams.
return new ArrayList<>(map.values());
}
}
Group Anagrams in C++
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// Use an unordered_map to group anagrams.
// The key is a canonical representation of an anagram group.
// The value is the list of strings in that group.
unordered_map<string, vector<string>> mp;
for (string& s : strs) {
// Create a frequency count of characters for the string s.
// This count will serve as the key.
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
// Convert the count vector to a string key.
// A separator is needed to distinguish between counts like (1, 12) and (11, 2).
string key = "";
for (int i = 0; i < 26; ++i) {
key += to_string(count[i]) + '#';
}
// Add the original string to the list associated with this key.
mp[key].push_back(s);
}
// Collect the grouped anagrams from the map's values.
vector<vector<string>> ans;
for (auto const& pair : mp) {
ans.push_back(pair.second);
}
return ans;
}
};
Group Anagrams in TypeScript
function groupAnagrams(strs: string[]): string[][] {
// Use a Map to group anagrams.
// The key is a string representation of the character counts.
// The value is an array of strings that are anagrams.
const map = new Map<string, string[]>();
const aCharCode = 'a'.charCodeAt(0);
for (const s of strs) {
// Create a character count array of size 26 for 'a' through 'z'.
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - aCharCode]++;
}
// Convert the character count array to a string to be used as a key.
// Using a separator is a good practice to ensure uniqueness.
const key = count.join('#');
// If the key is not in the map, create a new array.
if (!map.has(key)) {
map.set(key, []);
}
// Add the current string to the array for this key.
// The non-null assertion `!` is safe here because we just checked/set the key.
map.get(key)!.push(s);
}
// The values of the map are the arrays of grouped anagrams.
return Array.from(map.values());
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.