ยท 1 min read
Blind 75 - Group Anagram
compare the count of letters in each word and put group them in a map
Video
https://youtu.be/7KHKFqLPMbsProblem and Constraints
Given a set of strings. Return anagrams in group.
All Approaches and Explanations in English
O(n) time complexity. O(n) space complexity
O(N*26) time complexity.
compare the count of letters in each word and put group them in a map
Code, if any
Works but okay, okay
class Solution {
private String getLetterCount(String str){
int[] count = new int[26];
for(char c: str.toCharArray()){
count[c-'a']++;
}
return Arrays.toString(count);
}
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap<>();
for(String str: strs){
String letterCount = getLetterCount(str);
List<String> list = groups.getOrDefault(letterCount, new ArrayList<>());
list.add(str);
groups.put(letterCount, list);
}
return new ArrayList<>(groups.values());
}
}Optimizations: rather than: Arrays.toString(count); could have been: new String(count)
rather than:
List<String> list = groups.getOrDefault(letterCount, new ArrayList<>());
list.add(str);
groups.put(letterCount, list);could have been:
letterCount could be renamed as hash. #DDDgroups.computeIfAbsent(letterCount, k-> new ArrayList<>())
groups.get(letterCount).add(str);Related posts
- Blind 75 - Top K Frequent Elements - IMP Oct 30, 2022
- Blind 75 - Reverse LinkedList Nov 16, 2022
- Blind 75 - Same Tree Nov 16, 2022
Get new posts by email
No spam. Unsubscribe anytime. Or grab the RSS feed.
Mailto-based for now. ButtonDown / ConvertKit can replace this form later.