Count Anagram Groups
Medium arrays · hashing · strings
Description
Constraints
1 <= words <= 10000; words contain lowercase letters
Examples
Input: words = ["eat","tea","tan","ate","nat","bat"]
Output: 3
[eat,tea,ate], [tan,nat], [bat]
Hints (1)
- Two words are anagrams if their sorted letters match; use that as a group key.
Solutions
Sort each word and count distinct sorted keys. (requires "sort") · Time O(n*k log k) · Space O(n)
func countAnagramGroups(words []string) int {
groups := map[string]bool{}
for _, w := range words {
b := []byte(w)
sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
groups[string(b)] = true
}
return len(groups)
}
Sort each word and count distinct sorted keys. · Time O(n*k log k) · Space O(n)
function countAnagramGroups(words) {
const groups = new Set();
for (const w of words) {
groups.add([...w].sort().join(''));
}
return groups.size;
}
Sort each word and count distinct sorted keys. · Time O(n*k log k) · Space O(n)
function countAnagramGroups($words) {
$groups = [];
foreach ($words as $w) {
$chars = str_split($w);
sort($chars);
$groups[implode('', $chars)] = true;
}
return count($groups);
}
Sort each word and count distinct sorted keys. · Time O(n*k log k) · Space O(n)
def countAnagramGroups(words):
return len({"".join(sorted(w)) for w in words})
Sort each word and count distinct sorted keys. · Time O(n*k log k) · Space O(n)
function countAnagramGroups(words: string[]): number {
const groups = new Set<string>();
for (const w of words) {
groups.add([...w].sort().join(''));
}
return groups.size;
}
Create a free account to submit solutions, track progress and save problems.
Create account