Algo-Sim › Arrays & Hashing
Group Anagrams
Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Group words that are anagrams of each other, using the sorted word as a hash map key.
Problem
Given a list of words strs, put the words that are anagrams of one another (same letters, same counts) into the same group. Return the groups in any order.
Constraints
- 1 ≤ strs.length ≤ 10⁴
- 0 ≤ strs[i].length ≤ 100
- Words contain only lowercase English letters
Edge cases to test
- Empty strings group together:
["", ""] - A single word
- Words of different lengths never match
Follow-up questions
- Can you avoid sorting each word?
- Use the 26 letter counts as the key: O(n·k) instead of O(n·k log k) for n words of length k.
- What if the words don’t fit in memory?
- Stream them and write each to a file chosen by hash(key), then group file by file: the MapReduce shuffle, one extra pass over the data.
Solution
Java
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new LinkedHashMap<>();
for (String s : strs) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>(groups.values());
}Python
def group_anagrams(strs):
groups = {}
for s in strs:
key = ''.join(sorted(s))
groups.setdefault(key, []).append(s)
return list(groups.values())C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string> &strs) {
unordered_map<string, int> groups;
vector<vector<string>> result;
for (string s : strs) {
string chars = s;
sort(chars.begin(), chars.end());
string key = string(chars.begin(), chars.end());
if (!groups.count(key)) {
groups[key] = int(result.size());
result.push_back({});
}
result[groups[key]].push_back(s);
}
return result;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)