Find Words That Can Be Formed by Characters (LeetCode 1160): Solution and Explanation

Easy
Array
Hash Table
String
Counting

Given a list of words and a pool of letters, add up the lengths of the words that can be spelled from the pool, using each letter at most once per word.

Intuition

Think of chars as a rack of letter tiles. A word can be spelled if, for every letter, the word needs no more tiles than the rack holds. Order does not matter, only counts.

The rack is the same for every word, so count its letters once into 26 counters. Each word then gets a fresh set of 26 counters for what it has taken so far.

While spelling a word, the first letter whose count goes over the supply proves the word is impossible, so you can stop right there and move to the next word.

Approach: Letter counts with an early exit

  1. Count each letter of chars into have[26].
  2. For each word, start need[26] at zero.
  3. For each letter of the word, increment need for it. If need now exceeds have, the word cannot be formed: stop scanning it.
  4. If the word finished without running out, add its length to the total.
  5. Return the total.

Step-by-step example

words = ["cat","bt","hat","tree"], chars = "atach"
  1. The rack holds a×2, t×1, c×1, h×1.
  2. "cat" takes c, a and t without running out, so total = 3.
  3. "bt" asks for b, and the rack has no b, so it fails.
  4. "hat" takes h, a and t with a fresh rack, so total = 6.
  5. "tree" takes t, then asks for r, which the rack lacks, so it fails. Return 6.

Code: Python, Java, C++

1class Solution:
2    def countCharacters(self, words: List[str], chars: str) -> int:
3        have = [0] * 26
4        for c in chars:
5            have[ord(c) - 97] += 1
6        total = 0
7        for word in words:
8            need = [0] * 26
9            ok = True
10            for c in word:
11                k = ord(c) - 97
12                need[k] += 1
13                if need[k] > have[k]:
14                    ok = False
15                    break
16            if ok:
17                total += len(word)
18        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(|chars| + L)

L is the total number of letters across all words. Each letter is counted at most once, and resetting 26 counters per word is constant work.

Space

O(1)

Two arrays of 26 counters, whatever the input size.

Other approaches

Counter subtraction (time O(|chars| + L), space O(1))

In Python, Counter(word) - Counter(chars) is empty exactly when the word can be formed. It is short to write but always counts the whole word, with no early exit.

Remove letters from a copy of chars (time O(L * |chars|), space O(|chars|))

Copy chars into a list and remove one matching letter per character of the word. Each removal searches the list, so it is much slower for long inputs.

Common mistakes

  • Using up letters across words. Each word is checked against the full chars, so the supply resets for every word.
  • Only checking that each letter appears in chars. "aaa" needs three a's, not just one.
  • Forgetting to reset the per-word counters, which lets letters taken by an earlier word count against the next one.

Frequently asked questions

Do letters used by one word become unavailable for the next?

No. Every word is tested on its own against all of chars. Only within one word is each tile usable once.

Why use an array of 26 instead of a hash map?

The input is only lowercase English letters, so a fixed array is simpler and faster. A hash map gives the same result and is the natural choice for larger alphabets.

Is this the same idea as Ransom Note?

Yes. Ransom Note asks whether one word can be built from a magazine's letters; this problem runs the same check for many words and sums the lengths of those that pass.