Valid Anagram
Two strings are anagrams exactly when they contain the same letters the same number of times — order doesn't matter, only each character's frequency. So count every letter in the first string, then walk the second string decrementing those same counts; if the second string never demands a letter it doesn't have and every count lands back at zero, the frequencies matched exactly. Reach for it on any 'same letters, same frequencies' check.
Details
Animated on: s="anagram", t="nagaram" — is t an anagram of s?
Problem:Valid AnagramEasy
Pattern:Hashing and Frequency Maps
Strings
step 1 / 10
s="anagram" (idx0-6), t="nagaram" (idx7-13). Same length (7=7) — proceed.
1FUNCTION isAnagram(s, t):2 IF length of s != length of t: RETURN false3 count = an empty tally of characters4 FOR each ch in s: add 1 to count for ch5 FOR each ch in t:6 IF count for ch is 0 (or missing): RETURN false7 subtract 1 from count for ch8 END FOR9 RETURN true10END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 10 steps
- s="anagram" (idx0-6), t="nagaram" (idx7-13). Same length (7=7) — proceed.
- Build count from s: a appears 3x (idx0,2,5), n:1, g:1, r:1, m:1 → count={a:3,n:1,g:1,r:1,m:1}.
- t[0]='n'. count['n'] 1→0.
- t[1]='a'. count['a'] 3→2.
- t[2]='g'. count['g'] 1→0.
- t[3]='a'. count['a'] 2→1.
- t[4]='r'. count['r'] 1→0.
- t[5]='a'. count['a'] 1→0.
- t[6]='m'. count['m'] 1→0. Every count has now returned to zero.
- All counts zero — t is an anagram of s. Return true.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.