Bird
Raised Fist0
DSA Goprogramming

Anagram Check Techniques in DSA Go

Choose your learning style10 modes available
Mental Model
Two words are anagrams if they have the exact same letters in any order.
Analogy: Imagine two bags of letter tiles; if both bags have the same letters in the same amounts, they are anagrams.
word1: c -> a -> t -> null
word2: t -> a -> c -> null

Both have letters c, a, t but order differs.
Dry Run Walkthrough
Input: word1: "listen", word2: "silent"
Goal: Check if "listen" and "silent" are anagrams
Step 1: Count letters in "listen"
l:1, i:1, s:1, t:1, e:1, n:1
Why: We need to know how many times each letter appears in the first word
Step 2: Count letters in "silent"
s:1, i:1, l:1, e:1, n:1, t:1
Why: We count letters in the second word to compare with the first
Step 3: Compare both counts
Both have l:1, i:1, s:1, t:1, e:1, n:1
Why: If counts match exactly, words are anagrams
Result:
Words are anagrams because letter counts match exactly
Annotated Code
DSA Go
package main

import (
	"fmt"
)

func areAnagrams(s1, s2 string) bool {
	if len(s1) != len(s2) {
		return false // different lengths can't be anagrams
	}
	count := make(map[rune]int)
	for _, ch := range s1 {
		count[ch]++ // count letters in s1
	}
	for _, ch := range s2 {
		count[ch]-- // subtract letters found in s2
		if count[ch] < 0 {
			return false // more of ch in s2 than s1
		}
	}
	return true // all counts matched
}

func main() {
	word1 := "listen"
	word2 := "silent"
	if areAnagrams(word1, word2) {
		fmt.Println("Words are anagrams")
	} else {
		fmt.Println("Words are not anagrams")
	}
}
if len(s1) != len(s2) { return false }
Check length early to skip impossible cases
count[ch]++
Count each letter in first word
count[ch]--
Subtract count for each letter in second word
if count[ch] < 0 { return false }
If any letter count goes negative, words differ
return true
If all counts balanced, words are anagrams
OutputSuccess
Words are anagrams
Complexity Analysis
Time: O(n) because we count letters in both words once, where n is word length
Space: O(1) because the map size is limited to the alphabet size, which is constant
vs Alternative: Sorting both words takes O(n log n), so counting letters is faster and more efficient
Edge Cases
Empty strings
Returns true because two empty words are trivially anagrams
DSA Go
if len(s1) != len(s2) { return false }
Different lengths
Returns false immediately since lengths differ
DSA Go
if len(s1) != len(s2) { return false }
Same letters but different counts
Returns false because letter counts do not match
DSA Go
if count[ch] < 0 { return false }
When to Use This Pattern
When you need to check if two words have the same letters in any order, use the letter counting pattern because it efficiently compares letter frequencies.
Common Mistakes
Mistake: Only checking if sorted words are equal without handling case sensitivity
Fix: Convert both words to the same case before checking
Mistake: Not checking length first, causing unnecessary work
Fix: Add length check at start to quickly return false if lengths differ
Summary
Checks if two words have the same letters in the same amounts regardless of order
Use when you want to verify if two strings are anagrams efficiently
Counting letters and comparing counts is faster than sorting both words

Practice

(1/5)
1. What is the main idea behind checking if two strings are anagrams?
easy
A. Both strings have the same characters with the same frequency
B. Both strings have the same length only
C. Both strings start with the same character
D. Both strings contain vowels only

Solution

  1. Step 1: Understand anagram definition

    Anagrams are words or phrases made by rearranging letters of another, so they must have the same characters with the same counts.
  2. Step 2: Compare character frequency

    Checking if two strings have the same frequency of each character confirms if they are anagrams.
  3. Final Answer:

    Both strings have the same characters with the same frequency -> Option A
  4. Quick Check:

    Character frequency equality = Anagram check [OK]
Hint: Check if sorted strings are equal [OK]
Common Mistakes:
  • Only comparing string lengths
  • Ignoring character counts
  • Checking first characters only
2. Which Go code snippet correctly checks if two strings are anagrams by sorting?
easy
A. sort.Strings([]string{s1, s2}); return s1 == s2
B. s1Sorted := sort.Strings(strings.Split(s1, "")); s2Sorted := sort.Strings(strings.Split(s2, "")); return s1Sorted == s2Sorted
C. s1Sorted := strings.Split(s1, ""); sort.Strings(s1Sorted); s2Sorted := strings.Split(s2, ""); sort.Strings(s2Sorted); return strings.Join(s1Sorted, "") == strings.Join(s2Sorted, "")
D. return s1 == s2

Solution

  1. Step 1: Split strings into slices of characters

    Use strings.Split(s, "") to get slice of characters for sorting.
  2. Step 2: Sort slices and join back to strings

    Sort each slice with sort.Strings and join with strings.Join to compare sorted strings.
  3. Final Answer:

    Splitting, sorting slices, then joining for comparison -> Option C
  4. Quick Check:

    Sort slices and join = Correct anagram check [OK]
Hint: Split, sort slices, join, then compare [OK]
Common Mistakes:
  • Trying to sort strings directly (not allowed)
  • Comparing unsorted strings
  • Using sort.Strings on whole string instead of slice
3. What is the output of this Go code snippet?
func areAnagrams(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
}

fmt.Println(areAnagrams("listen", "silent"))
fmt.Println(areAnagrams("hello", "bello"))
medium
A. true false
B. false true
C. true true
D. false false

Solution

  1. Step 1: Count characters in first string

    Map counts characters in "listen": l=1, i=1, s=1, t=1, e=1, n=1.
  2. Step 2: Decrease counts for second string and check negatives

    For "silent", counts decrease to zero without negatives, so true. For "bello", 'b' not in map or count negative, so false.
  3. Final Answer:

    true false -> Option A
  4. Quick Check:

    Map count balance = true/false [OK]
Hint: Use map counts to verify character balance [OK]
Common Mistakes:
  • Not checking length first
  • Not returning false on negative count
  • Confusing rune and byte iteration
4. Identify the bug in this Go function that checks anagrams:
func isAnagram(s1, s2 string) bool {
    if len(s1) != len(s2) {
        return false
    }
    count := make(map[rune]int)
    for i := 0; i < len(s1); i++ {
        count[rune(s1[i])]++
        count[rune(s2[i])]--
    }
    for _, v := range count {
        if v != 0 {
            return false
        }
    }
    return true
}
medium
A. Not checking string lengths before counting
B. Using rune conversion on byte indexing may miscount multibyte characters
C. Missing return statement at the end
D. Using map with int keys instead of rune keys

Solution

  1. Step 1: Understand rune vs byte indexing in Go strings

    Indexing strings by byte (s1[i]) may split multibyte characters incorrectly, causing wrong rune counts.
  2. Step 2: Identify correct iteration method

    Use range over string to get runes properly instead of byte indexing with rune conversion.
  3. Final Answer:

    Using rune conversion on byte indexing may miscount multibyte characters -> Option B
  4. Quick Check:

    Byte indexing ≠ rune iteration for Unicode [OK]
Hint: Use 'for _, r := range s' to handle runes correctly [OK]
Common Mistakes:
  • Assuming byte indexing works for all characters
  • Ignoring Unicode multibyte characters
  • Not checking map values properly
5. Given a list of strings, which Go approach efficiently groups all anagrams together?
hard
A. Use string length as map key to group strings
B. Compare every pair of strings with nested loops checking character counts
C. Count vowels in each string and group by vowel count
D. Sort each string's characters and use the sorted string as a map key

Solution

  1. Step 1: Understand grouping anagrams by sorted keys

    Sorting characters of each string creates a unique key for all anagrams, allowing grouping in a map efficiently.
  2. Step 2: Compare with other methods

    Nested loops are slow (O(n²)), length or vowel count grouping is inaccurate for anagrams.
  3. Final Answer:

    Sort each string's characters and use the sorted string as a map key -> Option D
  4. Quick Check:

    Sorted string keys = efficient anagram grouping [OK]
Hint: Sort strings and group by sorted key [OK]
Common Mistakes:
  • Using nested loops causing slow performance
  • Grouping by length only misses anagrams
  • Grouping by vowels ignores consonants
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard