Browse curriculum

Anagram Check

Visualize checking if two strings are anagrams (contain same characters with same frequencies).

ONE SHARED TALLY

COUNT

l

0

i

1

s

2

t

3

e

4

n

5

s

0

i

1

l

2

e

3

n

4

t

5

Character counts

0

e

0

i

1

l

0

n

0

s

0

t

 

'l' in the first word → count 1.

Next

'i' in the first word → count 1.

First

Second

Intuition

Two strings are anagrams if they have the exact same characters with the exact same frequencies. We can use a hash map (or frequency array) to count characters in the first string and decrement for the second.

Concept

  • Frequency Map: Stores count of each character.
  • Process: +1 for char in String 1, -1 for char in String 2.
  • Result: If map is empty (or all zeros), it's an anagram.

How it Works

Algorithm:

  1. If lengths differ, return False.
  2. Create a frequency map.
  3. Loop through String 1: Increment count for each char.
  4. Loop through String 2: Decrement count for each char.
  5. If any count becomes negative (or char not found), return False.
  6. Return True.

Step-by-Step Breakdown

Watch the visualization:

  • See counts go UP as we scan String 1.
  • See counts go DOWN as we scan String 2.
  • If all counts return to 0, it's a match.

When to Use

  • Checking if two words are rearrangements of each other.
  • Grouping anagrams from a list.

When NOT to Use

  • When order matters (not anagrams).

How to Identify

"Rearrange characters", "Permutation of string".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

Why is counting characters better than sorting both strings?

Sorting is O(N log N) while a frequency table is a single O(N) pass. The counting version also tells you which character is out of balance, which sorting does not.


Why increment for one string and decrement for the other?

It avoids a second table and a comparison step. If the strings are anagrams every count returns to zero, so the first non-zero entry is an immediate no.


What should I check first?

The lengths. Strings of different lengths can never be anagrams, and rejecting them up front removes any need to reason about counts that could not balance.