Go Program to Check Anagram with Example and Explanation
sort.Slice() after converting to rune slices, or by counting character frequencies using maps and comparing the counts.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" "sort" ) func isAnagram(s1, s2 string) bool { if len(s1) != len(s2) { return false } r1 := []rune(s1) r2 := []rune(s2) sort.Slice(r1, func(i, j int) bool { return r1[i] < r1[j] }) sort.Slice(r2, func(i, j int) bool { return r2[i] < r2[j] }) for i := range r1 { if r1[i] != r2[i] { return false } } return true } func main() { fmt.Println(isAnagram("listen", "silent")) fmt.Println(isAnagram("hello", "world")) fmt.Println(isAnagram("aabbcc", "abcabc")) }
Dry Run
Let's trace the example "listen" and "silent" through the code
Check length
len("listen") = 6, len("silent") = 6, lengths match, continue
Convert to rune slices
r1 = ['l','i','s','t','e','n'], r2 = ['s','i','l','e','n','t']
Sort rune slices
sorted r1 = ['e','i','l','n','s','t'], sorted r2 = ['e','i','l','n','s','t']
Compare sorted slices
All characters match at each index, return true
| Index | r1[i] | r2[i] | Match |
|---|---|---|---|
| 0 | e | e | yes |
| 1 | i | i | yes |
| 2 | l | l | yes |
| 3 | n | n | yes |
| 4 | s | s | yes |
| 5 | t | t | yes |
Why This Works
Step 1: Length Check
If the two strings have different lengths, they cannot be anagrams, so we return false immediately.
Step 2: Sorting Characters
We convert strings to rune slices and sort them so that letters are in order, making it easy to compare.
Step 3: Comparing Sorted Strings
If every character in the sorted slices matches, the strings are anagrams; otherwise, they are not.
Alternative Approaches
package main import "fmt" func isAnagramMap(s1, s2 string) bool { if len(s1) != len(s2) { return false } count := make(map[rune]int) for _, ch := range s1 { count[ch]++ } for _, ch := range s2 { count[ch]-- if count[ch] < 0 { return false } } return true } func main() { fmt.Println(isAnagramMap("listen", "silent")) fmt.Println(isAnagramMap("hello", "world")) fmt.Println(isAnagramMap("aabbcc", "abcabc")) }
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting both strings takes O(n log n) time where n is the string length, which dominates the runtime.
Space Complexity
We create rune slices of size n for sorting, so space complexity is O(n).
Which Approach is Fastest?
The map counting method runs in O(n) time and uses O(n) space, often faster for large inputs than sorting.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting | O(n log n) | O(n) | Simple code, small to medium strings |
| Map Counting | O(n) | O(n) | Large strings, better performance |