Visualize

Pattern visualizer

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. Animated on: s="anagram", t="nagaram" — is t an anagram of s?.

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]
line 2

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

Where to practice Strings