Member-only story
Leetcode 49 Group anagrams
2 min readFeb 25, 2020
Providing not the fastest solution, but normalization of anagrams is fast enough, otherwise go with the hash function as alternative:
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// Another possible alternative is to hash the string by
// assigning an integer to each letter
// better if each integer is prime, shoudl definitely not be
// one, and multiply all the letter values
// Store in HashMap<Long, List<String>> and at the end
// convert to List<List<String>>
Map<String, List<String>> res = new HashMap<>();
int n = strs.length;
for (int i = 0; i < n; i++) {
String s = strs[i];
String norm = normalize(s);
boolean added = false;
if (res.containsKey(norm)) {
res.get(norm).add(s);
} else {
res.put(norm, new ArrayList<>());
res.get(norm).add(s);
}
}
List<List<String>> lstRes = new ArrayList<>();
for (String norm : res.keySet()) {
lstRes.add(res.get(norm));
}
return lstRes;
// alternative solution 2 (slow, map of map)
// Map<Map<Character, Integer>, List<String>> res =
// new HashMap<>();
// int n = strs.length;
// for (int i = 0; i < n; i++) {
// Map<Character, Integer> map = count(strs[i]);
// boolean added = false;
// for (Map<Character, Integer> m : res.keySet()) {
// if…