Valid Anagram
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Decide whether two strings contain exactly the same letters with the same counts, in any order.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1If order does not matter, what does matter about each letter?
- Hint 2Count how many times each letter appears in each word.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Two Scrabble players each pour out their bag of tiles. Are the two bags the same set of tiles? You do not arrange them in order. You just tick off: take a tile from bag A and cross out the same tile in bag B. If every tile gets crossed out and nothing is left, the bags match.
- The obvious way
Sort both words and compare them: O(n log n).
- The key insight
Two words are anagrams exactly when their letter counts are equal. Count the first word's letters up, then cross them out using the second word. If a letter would go below zero, or the lengths differ, they are not anagrams.
- The algorithm
- Different lengths? Not anagrams. Stop.
- Count every letter of the first word on a tally sheet.
- Walk through the second word and cross out each letter from the tally.
- A letter you cannot cross out (tally already 0)? Not anagrams. Otherwise they are.
Watch it run
Examplefirst = "rat", second = "tar"
Count the first word: one r, one a, one t.
tally: r=1 a=1 t=1
Where people slip
- Without the length check, "a" and "ab" can slip through some counting methods.
- For Unicode text use a dictionary tally instead of 26 slots.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
from collections import Counter
def is_anagram(first, second):
if len(first) != len(second):
return False
tally = Counter(first) # letters of the first word
for letter in second:
tally[letter] -= 1 # cross one out
if tally[letter] < 0: # second has a letter first does not
return False
return TrueNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.