Browse Curriculum

Anagram Check

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

Ready to check Anagram.
String 1
l
i
s
t
e
n
String 2
s
i
l
e
n
t
Frequency Map
Map is empty

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".

Frequently Asked Questions

What is Anagram Check?

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


What is the time complexity of Anagram Check?

The time complexity is: Best case varies, Average case O(N), Worst case varies. Space complexity is varies.