BeginnerCoder

Lesson 18 — Anagram check

Anagrams: compare letter counts

Two words are anagrams if they use exactly the same letters the same number of times ("listen" / "silent"). Instead of sorting, count each letter in a dict and compare the two dicts. d.get(key, 0) returns the stored value, or 0 if the key is new.

counts = {}
counts["a"] = counts.get("a", 0) + 1   # {'a': 1}

Counting is O(n); sorting is O(n log n).

Why it matters: "count with a dict, then compare" solves a whole family of problems: duplicates, most common item, matching inventories.

Want it another way?
Task

Finish letter_counts(word) by counting each character. Expected: True, False, True.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Algorithms Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.