Group Anagrams
LeetCode 49 · View on LeetCode
Sort each string to create a canonical key. All anagrams produce the same sorted key, so they land in the same map bucket.
package main
import (
"fmt"
"sort"
)
func groupAnagrams(strs []string) [][]string {
groups := make(map[string][]string)
for _, s := range strs {
b := []byte(s)
sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
key := string(b)
groups[key] = append(groups[key], s)
}
result := make([][]string, 0, len(groups))
for _, g := range groups {
result = append(result, g)
}
return result
}
func main() {
fmt.Println(groupAnagrams([]string{"eat", "tea", "tan", "ate", "nat", "bat"}))
// [[eat tea ate] [tan nat] [bat]]
}