progress

~/problems / Arrays & hashing / Hash maps and counting

Valid Anagram

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

A word game accepts a guess only if it uses exactly the same letters as the given word, the same number of times, possibly shuffled.

Write is_rearrangement(a, b) -> bool that returns whether b is a reordering of a.

is_rearrangement("listen", "silent")   # True
is_rearrangement("aab", "abb")         # False  (different counts of 'a' and 'b')
is_rearrangement("cat", "cats")        # False
is_rearrangement("", "")               # True

Up to 2 * 10^5 lowercase letters each. ⭐ Bonus: a speed test earns a star in O(n).

Show hint

two strings are reorderings exactly when every letter occurs equally often in both. Tally one, untally the other.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc