Sort Each String as Key
Intuition
Two strings are anagrams if and only if their sorted forms are identical. We can use the sorted version of each string as a hash map key. For every string in the input, sort it, then add the original string to the list associated with that sorted key. Finally, collect all the lists from the map.
Algorithm
- Create a hash map where keys are sorted strings and values are lists of original strings.
- For each string in the input, sort its characters to produce a key.
- Add the original string to the list mapped to that key.
- Return all values from the hash map as the result.
O(n * k log k) where n is the number of strings and k is the maximum string lengthSpaceO(n * k)Code (C++ · Java · Python · Go)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (const string& s : strs) {
string key = s;
sort(key.begin(), key.end());
groups[key].push_back(s);
}
vector<vector<string>> result;
for (auto& [key, group] : groups) {
result.push_back(group);
}
return result;
}
};class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
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());
}
}from collections import defaultdict
def groupAnagrams(strs: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for s in strs:
key = "".join(sorted(s))
groups[key].append(s)
return list(groups.values())import "sort"
func groupAnagrams(strs []string) [][]string {
groups := make(map[string][]string)
for _, s := range strs {
bytes := []byte(s)
sort.Slice(bytes, func(i, j int) bool { return bytes[i] < bytes[j] })
key := string(bytes)
groups[key] = append(groups[key], s)
}
result := make([][]string, 0, len(groups))
for _, group := range groups {
result = append(result, group)
}
return result
}