package main import ( "fmt" "sort" "strings" ) func areAnagrams(s1, s2 string) bool { if len(s1) != len(s2) { return false } arr1 := strings.Split(s1, "") arr2 := strings.Split(s2, "") sort.Strings(arr1) sort.Strings(arr2) for i := range arr1 { if arr1[i] != arr2[i] { return false } } return true } func main() { fmt.Println(areAnagrams("listen", "silent")) fmt.Println(areAnagrams("hello", "bello")) }
The function sorts both strings' characters and compares them. If they match, they are anagrams.
"listen" and "silent" are anagrams, so true. "hello" and "bello" differ, so false.
package main import "fmt" func areAnagrams(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]-- if freq[ch] < 0 { return false } } return true } func main() { fmt.Println(areAnagrams("triangle", "integral")) fmt.Println(areAnagrams("apple", "papel")) }
The frequency map counts characters in s1 and subtracts counts for s2.
If any count goes below zero, strings are not anagrams.
Both pairs are anagrams, so output is true true.
package main import "fmt" func areAnagrams(s1, s2 string) bool { if len(s1) != len(s2) { return false } var freq map[rune]int for _, ch := range s1 { freq[ch]++ } for _, ch := range s2 { freq[ch]-- if freq[ch] < 0 { return false } } return true } func main() { fmt.Println(areAnagrams("abc", "cab")) }
The map freq is declared but not initialized, so it is nil.
Writing to a nil map causes a runtime panic with message "assignment to entry in nil map".
package main import ( "fmt" "strings" ) func areAnagrams(s1, s2 string) bool { if len(s1) != len(s2) { return false } freq := make(map[rune]int) for _, ch := range strings.ToLower(s1) { freq[ch]++ } for _, ch := range strings.ToLower(s2) { freq[ch]-- if freq[ch] < 0 { return false } } return true } func main() { fmt.Println(areAnagrams("Dormitory", "DirtyRoom")) fmt.Println(areAnagrams("Hello", "Olelh")) }
Converting both strings to lowercase makes the comparison case-insensitive.
Both pairs are anagrams ignoring case, so output is true true.
The frequency map approach processes each character once in both strings, so 2n operations.
Map insertions and lookups are average O(1), so total is O(n).
