Valid Anagram
Master this topic with zero to advance depth.
Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Visual Representation
s = "anagram", t = "nagaram"
Method: Count each character
a: 3, n: 1, g: 1, r: 1, m: 1 (in s)
a: 3, n: 1, g: 1, r: 1, m: 1 (in t)
Counts Match -> TrueExamples
Level I: Sorting
Intuition
Anagrams have the same characters in the same frequency. If we sort both strings, they should be identical.
Detailed Dry Run
s="abc", t="cba" s.sort() -> "abc" t.sort() -> "abc" "abc" == "abc" -> True
Level II: HashMap (Character Count)
Intuition
Count character frequencies using a HashMap. This handles Unicode characters more naturally than a fixed-size array.
Detailed Dry Run
s="aa", t="a" Map {a: 2} from s Map {a: 2-1=1} from t Length mismatch detected early -> return False
Level III: Fixed-Size Array (Optimal)
Intuition
Since we only have 26 lowercase letters, an array of size 26 is more efficient than a HashMap.
Detailed Dry Run
arr = [0]*26 s="a": arr[0]++ -> [1,0...] t="a": arr[0]-- -> [0,0...] All indices zero -> True
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.