How to check if two strings are anagram (same letters different words) in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func areAnagram(s1, s2 string) bool {
    if len(s1) != len(s2) {
        return false
    }

    freq := make(map[rune]int)

    for _, ch := range s1 {
        freq[ch]++
    }
    for _, ch := range s2 {
        freq[ch]--
    }

    for _, count := range freq {
        if count != 0 {
            return false
        }
    }
    
    return true
}

func main() {
    fmt.Println(map[bool]string{true: "yes", false: "no"}[areAnagram("golang", "langgo")])
    fmt.Println(map[bool]string{true: "yes", false: "no"}[areAnagram("golang", "langog")])
    fmt.Println(map[bool]string{true: "yes", false: "no"}[areAnagram("golang", "galang")])
}



/*
run:

yes
yes
no

*/

 



answered Nov 13, 2025 by avibootz
...