Anagram Check Techniques in DSA Go - Time & Space Complexity
We want to understand how the time needed to check if two words are anagrams changes as the words get longer.
How does the work grow when the input size increases?
Analyze the time complexity of the following 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
}
This code checks if two strings are anagrams by counting characters in the first string and then subtracting counts using the second string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two loops each going through all characters of the strings.
- How many times: Each loop runs once over all characters, so twice over the input length.
As the strings get longer, the number of steps grows roughly twice as fast because we check each character twice.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps |
| 100 | About 200 steps |
| 1000 | About 2000 steps |
Pattern observation: The work grows linearly with input size, doubling because of two passes.
Time Complexity: O(n)
This means the time to check anagrams grows directly in proportion to the length of the strings.
[X] Wrong: "Sorting both strings is always faster for anagram checks."
[OK] Correct: Sorting takes more time (O(n log n)) compared to counting characters (O(n)), so counting is usually faster.
Understanding how to efficiently check anagrams shows you can choose the right approach for string problems, a useful skill in many coding challenges.
"What if we used sorting of both strings instead of counting? How would the time complexity change?"
Practice
Solution
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.Step 2: Compare character frequency
Checking if two strings have the same frequency of each character confirms if they are anagrams.Final Answer:
Both strings have the same characters with the same frequency -> Option AQuick Check:
Character frequency equality = Anagram check [OK]
- Only comparing string lengths
- Ignoring character counts
- Checking first characters only
Solution
Step 1: Split strings into slices of characters
Use strings.Split(s, "") to get slice of characters for sorting.Step 2: Sort slices and join back to strings
Sort each slice with sort.Strings and join with strings.Join to compare sorted strings.Final Answer:
Splitting, sorting slices, then joining for comparison -> Option CQuick Check:
Sort slices and join = Correct anagram check [OK]
- Trying to sort strings directly (not allowed)
- Comparing unsorted strings
- Using sort.Strings on whole string instead of slice
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"))Solution
Step 1: Count characters in first string
Map counts characters in "listen": l=1, i=1, s=1, t=1, e=1, n=1.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.Final Answer:
true false -> Option AQuick Check:
Map count balance = true/false [OK]
- Not checking length first
- Not returning false on negative count
- Confusing rune and byte iteration
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
}Solution
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.Step 2: Identify correct iteration method
Use range over string to get runes properly instead of byte indexing with rune conversion.Final Answer:
Using rune conversion on byte indexing may miscount multibyte characters -> Option BQuick Check:
Byte indexing ā rune iteration for Unicode [OK]
- Assuming byte indexing works for all characters
- Ignoring Unicode multibyte characters
- Not checking map values properly
Solution
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.Step 2: Compare with other methods
Nested loops are slow (O(n²)), length or vowel count grouping is inaccurate for anagrams.Final Answer:
Sort each string's characters and use the sorted string as a map key -> Option DQuick Check:
Sorted string keys = efficient anagram grouping [OK]
- Using nested loops causing slow performance
- Grouping by length only misses anagrams
- Grouping by vowels ignores consonants
Ready to prove it?
Pass the test and this pattern moves unknown
