Skip to content

Instantly share code, notes, and snippets.

@karthick18
Created March 20, 2024 03:05
Show Gist options
  • Save karthick18/804dcbac6edb147ca98990c463194365 to your computer and use it in GitHub Desktop.
Save karthick18/804dcbac6edb147ca98990c463194365 to your computer and use it in GitHub Desktop.
Anagram group
package main
import (
"fmt"
"strings"
)
func frequencyHash(word string) string {
frequencyTable := [26]int{}
for _, b := range word {
ascii := int(b)
//tolower
if ascii >= int('A') && ascii <= int('Z') {
ascii = int('a') + (ascii - int('A'))
}
ascii -= int('a')
frequencyTable[ascii]++
}
// convert the frequency table to hash
hash := []string{}
for _, v := range frequencyTable {
hash = append(hash, fmt.Sprintf("%s", v))
}
return strings.Join(hash, "-")
}
func group_anagrams(words []string) [][]string {
m := make(map[string][]string)
for _, word := range words {
h := frequencyHash(word)
m[h] = append(m[h], word)
}
res := [][]string{}
for _, groups := range m {
res = append(res, groups)
}
return res
}
func main() {
words := []string{"eat", "tea", "tan", "ate", "bak", "ant"}
res := group_anagrams(words)
fmt.Println("anagram groups", res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment