Medium: Interview Core · Problem 60 of 82

Can You Spell It?

MediumStandard LibraryPython

Write can_make(word, letters) that returns True if the word can be spelled using the characters of letters, where each character in letters can be used at most once, and False otherwise. Case matters.

can_make("hello", "hleolxy") is True. can_make("hello", "helo") is False (there is only one l).

Understand the problem

Think about counts, not just which letters appear.

Why is all(ch in letters for ch in word) not enough?

  1. It is too slow
  2. It ignores how many times each letter is available
  3. It only works for numbers

"hello" needs two ls. all(ch in "helo" ...) is true because every letter appears at least once, but there is only one l. The check must compare counts.

What does Counter("hello") - Counter("helo") contain?

  1. Counter({"l": 1})
  2. Counter() (empty)
  3. Counter({"l": -1})

Counter subtraction keeps only positive counts. "hello" has two l, "helo" has one, so one l is left over: that is the missing letter. If nothing is missing, the result is empty (and falsy).

Write the solution

Return a boolean.

def can_make(word, letters):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What would be left over if you took away from the word everything the letters can provide?

Hint 2: the shape of the answer

not (Counter(word) - Counter(letters)): the subtraction is empty exactly when every needed letter is available often enough.

Reflect

Solution

from collections import Counter

def can_make(word, letters):
    return not (Counter(word) - Counter(letters))

Another way: compare counts letter by letter

from collections import Counter

def can_make(word, letters):
    available = Counter(letters)
    return all(available[ch] >= count for ch, count in Counter(word).items())

What this tests: collections.Counter, multisets, Counter arithmetic (- drops non-positive counts), truthiness of an empty Counter.

Multiset thinking: a set remembers whether an item is present; a Counter remembers how many. When repeats matter, use a Counter.

The truthiness trick: an empty Counter (like any empty container) is falsy, so not (a - b) reads as "nothing is missing". It is short, but spell it out in a comment the first time.

Cost: O(len(word) + len(letters)).

What an interviewer might ask next: Are two words anagrams? (Counter(a) == Counter(b).) And what is the maximum number of copies of a word you can build from the letters? (The minimum over letters of available // needed.)