Question
Given two strings, check if one is an anagram of the other. An anagram means both strings contain the same characters, just in a different order.
You must return true
if they are anagrams, false
otherwise.
Example
Input: "listen", "silent"
Output: true
Explanation: Both strings use the same letters.
Input: "rat", "car"
Output: false
Explanation: The characters don't match.
Input: "a", "a"
Output: true
Explanation: Same one-character string.
My Notes
- Compare string lengths first — quick fail if different.
- Use a hash map to count characters in the first string.
- Then subtract counts using the second string.
- If any character is missing or goes below zero, return
false
. - If the map is empty at the end, the strings are valid anagrams.
package main import ( "fmt" ) func main() { result := isAnagram("anagram", "nagaram") fmt.Println(result) } func isAnagram(s string, t string) bool { lookup := make(map[rune]int) if len(s) != len(t) { return false } for _, ch := range s { lookup[ch]++ } for _, ch := range t { if _, ok := lookup[ch]; !ok { return false } lookup[ch]-- if lookup[ch] == 0 { delete(lookup, ch) } } return true }