DSA Factory
Free Strings lessonsStrings · Stage 1 · Counting characters · Step 4

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 the pile: that's your supply.
Spend one per letter: run out and it's a no.
word = "aa", pile = "aab"
ab
supply
2
1

Count what's in the pile: two a's and one b. That's your supply.

Move 1 of 4

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.

Only running short matters: spares are fine.
In code
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 True
Quick check

Your pile has the letters of "aab". Can you spell "aba"?

  1. AYes
  2. BNo: the order is different
  3. CNo: you need another a
Show the answer

Yes. "aba" needs two a's and one b, and "aab" has exactly that.

Your problem

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.

Example
word = "aa", pile = "aab" → true

0 ≤ lengths ≤ 1,000,000 · only a to z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve