Valid Anagram
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Arrays & Hashing.
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
Input: s = "anagram", t = "nagaram"
Output: true
Input: s = "rat", t = "car"
Output: false
Approach 1
Level I: Sorting
Intuition
Anagrams have the same characters in the same frequency. If we sort both strings, they should be identical.
⏱ O(N log N) where N is string length.💾 O(1) or O(N) depending on sort implementation.
Detailed Dry Run
s="abc", t="cba"
s.sort() -> "abc"
t.sort() -> "abc"
"abc" == "abc" -> True
Approach 2
Level II: HashMap (Character Count)
Intuition
Count character frequencies using a HashMap. This handles Unicode characters more naturally than a fixed-size array.
⏱ O(N)💾 O(1) - finite character set size.
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
Approach 3
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.
⏱ O(N)💾 O(1) - fixed 26 integers.
Detailed Dry Run
arr = [0]*26
s="a": arr[0]++ -> [1,0...]
t="a": arr[0]-- -> [0,0...]
All indices zero -> True
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.