← Practice
πŸ“– String algorithmsstrings-valid-anagram
LessonΒ·difficulty 2/5Β·~15 min

Strings: valid anagram

Strings: valid anagram

An anagram is just the same multiset of letters wearing a different hat. "listen" and "silent" are anagrams; "rat" and "car" are not. So the question "is t an anagram of s?" is really "do s and t use the exact same letters the exact same number of times?"

The fast way to answer that is to count. Tally every character in s, then walk t knocking those tallies back down. If the books balance to zero, it's an anagram.

python
from collections import Counter
Counter("anagram") == Counter("nagaram")   # True

No need to sort (that's O(n log n)); counting is a single O(n) pass.

Your task

Write is_anagram(s, t) that returns True if t is an anagram of s and False otherwise. Two empty strings count as anagrams of each other.

python
is_anagram("anagram", "nagaram")   # True
is_anagram("rat", "car")           # False
is_anagram("", "")                 # True
is_anagram("a", "ab")              # False  (different lengths)

Hint: if the lengths differ, you can bail out immediately. Otherwise compare character counts.

Tests

  • classic anagram
  • not an anagram
  • both empty
  • different lengths
  • same letters reordered (hidden)
  • one letter off (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.