AI Hints
Home›DSA in Python Tutorial›Anagrams and Review
DSA in Python · Lesson 28 of 132

Practice: Valid Anagram

Same letters, different order.

⏱ 2 min read▶ Video at 32:07🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

Two words are anagrams if they use exactly the same letters, the same number of times. Listen and silent. Heart and earth. Pause, and think of two different ways to check.

Practice: Valid Anagram
From the video: Practice: Valid Anagram
  • Same letters, same counts
  • listen / silent
  • Two ways to check

Sort, or count

The first way sorts both words, and compares them. Sorting is O of N log N. The second way counts the letters in each word, and compares the counts. Counting is O of N, so it's faster for long words. Run it. Both agree. Listen and silent are anagrams. Apple and pale are not.

anagram.pypython
from collections import Counter

def anagram_sort(a, b):
    return sorted(a) == sorted(b)

def anagram_count(a, b):
    return Counter(a) == Counter(b)

for a, b in [("listen", "silent"), ("apple", "pale")]:
    print(a, b, anagram_sort(a, b), anagram_count(a, b))
Output
listen silent True True
apple pale False False

Which one?

Both are correct, and both are short. Sorting is simpler to explain, and uses less memory for short words. Counting wins for long text. In an interview, give one, and mention the other with its Big O. That shows you understand the trade off.

keyvalue
sorted(a) == sorted(b)O(n log n)
Counter(a) == Counter(b)O(n)
Short wordseither is fine
Interviewmention both

Summary

Anagrams have the same letter counts. Compare sorted letters, or compare Counters. Next, grouping a whole list of words into anagram families.

Key takeaways
  • Sort and compare
  • Count and compare
  • O(n log n) vs O(n)
Next up: Practice: Group Anagrams — a key for each family