0
0
GoProgramBeginner · 2 min read

Go Program to Check Anagram with Example and Explanation

In Go, you can check anagrams by sorting both strings and comparing them with sort.Slice() after converting to rune slices, or by counting character frequencies using maps and comparing the counts.
📋

Examples

Input"listen", "silent"
Outputtrue
Input"hello", "world"
Outputfalse
Input"aabbcc", "abcabc"
Outputtrue
🧠

How to Think About It

To check if two words are anagrams, think about whether they have the same letters in the same amounts. You can either sort the letters and see if the sorted results match, or count how many times each letter appears in both words and compare those counts.
📐

Algorithm

1
Get two input strings.
2
If their lengths differ, return false immediately.
3
Convert both strings to rune slices and sort them.
4
Compare the sorted slices; if they are equal, return true, else false.
💻

Code

go
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"))
}
Output
true false true
🔍

Dry Run

Let's trace the example "listen" and "silent" through the code

1

Check length

len("listen") = 6, len("silent") = 6, lengths match, continue

2

Convert to rune slices

r1 = ['l','i','s','t','e','n'], r2 = ['s','i','l','e','n','t']

3

Sort rune slices

sorted r1 = ['e','i','l','n','s','t'], sorted r2 = ['e','i','l','n','s','t']

4

Compare sorted slices

All characters match at each index, return true

Indexr1[i]r2[i]Match
0eeyes
1iiyes
2llyes
3nnyes
4ssyes
5ttyes
💡

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

Frequency Counting with Maps
go
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"))
}
This method uses a map to count characters, which can be faster for large strings and avoids sorting overhead.

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.

ApproachTimeSpaceBest For
SortingO(n log n)O(n)Simple code, small to medium strings
Map CountingO(n)O(n)Large strings, better performance
💡
Use rune slices when sorting strings in Go to handle Unicode characters correctly.
⚠️
Forgetting to check string lengths first can cause unnecessary work or incorrect results.