Enough letters?
Check whether one word can be spelled from another's letters. About 7 minutes.
Letters as a supply
You're cutting letters out of a magazine to spell a message. Can you spell the word with the letters you have?
Count the letters in your pile: that's your supply. Then go through the word you want to spell, spending one letter from the supply for each character. If you ever need a letter you've run out of, the answer is no.
Count what's in the pile: two a's and one b. That's your supply.
Leftovers are fine
Unlike an anagram, you don't have to use every letter in the pile. Spare letters don't matter at all. The only thing that can go wrong is running short of one you need.
So you never compare the two words' lengths or check that everything cancels. You just check that no letter's supply goes below zero.
supply = {}
for ch in pile:
supply[ch] = supply.get(ch, 0) + 1
for ch in word:
if supply.get(ch, 0) == 0:
return False
supply[ch] -= 1
return TrueYour pile has the letters of "aab". Can you spell "aba"?
- AYes
- BNo: the order is different
- CNo: you need another a
Show the answer
Yes. "aba" needs two a's and one b, and "aab" has exactly that.
Can you spell it?
You get a word and a pile of letters (as a string). Each letter in the pile can be used once. Return true if the word can be spelled with letters from the pile, and false otherwise.
word = "aa", pile = "aab" → true
0 ≤ lengths ≤ 1,000,000 · only a to z