DevPath

← All problems

Count Anagram Groups

Medium arrays · hashing · strings

Description

Given a list of words, return the number of distinct groups where words in the same group are anagrams of one another.

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)
}

Create a free account to submit solutions, track progress and save problems.

Create account