DSA Tracker

Visualize

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

a
[0]
n
[1]
a
[2]
g
[3]
r
[4]
a
[5]
m
[6]
n
[7]
a
[8]
g
[9]
a
[10]
r
[11]
a
[12]
m
[13]

s="anagram" (idx0-6), t="nagaram" (idx7-13). Same length (7=7) — proceed.

Pseudocode
1FUNCTION isAnagram(s, t):
2 IF length of s != length of t: RETURN false
3 count = an empty tally of characters
4 FOR each ch in s: add 1 to count for ch
5 FOR each ch in t:
6 IF count for ch is 0 (or missing): RETURN false
7 subtract 1 from count for ch
8 END FOR
9 RETURN true
10END FUNCTION

← / → step · space play · Home restart

Every step in words

Show all 10 steps
  1. s="anagram" (idx0-6), t="nagaram" (idx7-13). Same length (7=7) — proceed.
  2. 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}.
  3. t[0]='n'. count['n'] 1→0.
  4. t[1]='a'. count['a'] 3→2.
  5. t[2]='g'. count['g'] 1→0.
  6. t[3]='a'. count['a'] 2→1.
  7. t[4]='r'. count['r'] 1→0.
  8. t[5]='a'. count['a'] 1→0.
  9. t[6]='m'. count['m'] 1→0. Every count has now returned to zero.
  10. 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.