Find Words That Can Be Formed by Characters

Easy Arrays & Hashing Hashing

Find Words That Can Be Formed by Characters is a easy arrays & hashing problem solved with the hashing pattern. The best approach, optimal (letter counts), runs in O(C + W · L) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (cross letters off a copy) up.

Problem

You are given an array of strings words and a string chars. Think of chars as a bag of letter tiles.

A word is buildable if you can spell it with tiles from the bag, using each tile at most once. In other words, for every letter, the word must not contain it more times than chars does. Each word is checked on its own: the bag is full again for every word.

Return the sum of the lengths of all buildable words in words. If none of them can be built, return 0.

Examples

Example 1

Input
words = ["bat", "tab", "tub", "boat"], chars = "tabo"
Output
10
Why
"bat", "tab" and "boat" only use letters that chars has, so they count: 3 + 3 + 4 = 10. "tub" needs a u, and chars has none.

Example 2

Input
words = ["apple", "pale", "leap", "pal"], chars = "alpe"
Output
11
Why
chars has a single p, but "apple" needs two, so it is out. "pale", "leap" and "pal" all fit: 4 + 4 + 3 = 11.

Example 3

Input
words = ["zz", "z"], chars = "z"
Output
1
Why
Each letter of chars may be used once per word. "zz" needs two z's, so only "z" counts.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • words[i] and chars contain only lowercase English letters

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 19 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (cross letters off a copy)O(W · L · C)O(C)
Sort and matchO(C log C + W · (L log L + C))O(L + C)
Optimal (letter counts)O(C + W · L)O(1)

1Brute force (cross letters off a copy)

TimeO(W · L · C)W words, each with up to L letters, and every letter searches (and removes from) a pile of up to C tiles.
SpaceO(C)One copy of chars per word, reused.

Treat chars as a pile of letter tiles. For each word, make a fresh copy of the pile and go through the word one letter at a time: find that letter in the pile and take it out. If some letter cannot be found, the word cannot be built. If every letter was found, add the word's length to the answer. Each search scans the pile, so this is slow-ish, but it mirrors the problem statement exactly.

  1. Set total = 0.
  2. For each word, copy chars into a mutable pile.
  3. For each letter of the word, look for it in the pile. If it is missing, the word fails; otherwise remove that one tile.
  4. If the word never failed, add its length to total. Return total.
class Solution {
    public int countCharacters(String[] words, String chars) {
        int total = 0;
        for (String word : words) {
            StringBuilder pile = new StringBuilder(chars);
            boolean ok = true;
            for (char c : word.toCharArray()) {
                int at = pile.indexOf(String.valueOf(c));
                if (at < 0) {
                    ok = false;
                    break;
                }
                pile.deleteCharAt(at);
            }
            if (ok) total += word.length();
        }
        return total;
    }
}

2Sort and match

TimeO(C log C + W · (L log L + C))Sorting chars once, then per word a sort of its letters and one pass over the sorted pool.
SpaceO(L + C)The sorted pool and the sorted copy of the current word.

Sort the letters of chars once. For a word, sort its letters too. Now the word fits exactly when its sorted letters appear, in order, inside the sorted chars, as a subsequence: equal letters sit next to each other in both, so matching them left to right uses each tile of chars at most once. Walk two pointers: move through chars, and every time the current chars letter equals the next needed word letter, consume it. The word fits if all its letters get consumed.

  1. Sort chars into an array pool.
  2. For each word: sort its letters, then set i = 0 (in the word) and walk j over pool.
  3. When pool[j] equals word[i], advance i. Stop once i reaches the word's length.
  4. If i reached the end of the word, add its length. Return the total.
class Solution {
    public int countCharacters(String[] words, String chars) {
        char[] pool = chars.toCharArray();
        Arrays.sort(pool);
        int total = 0;
        for (String word : words) {
            char[] w = word.toCharArray();
            Arrays.sort(w);
            int i = 0;
            for (int j = 0; j < pool.length && i < w.length; j++) {
                if (pool[j] == w[i]) i++;
            }
            if (i == w.length) total += w.length;
        }
        return total;
    }
}

3Optimal (letter counts)

TimeO(C + W · L)One pass over chars, then one pass over each word (plus a 26-entry copy per word, which is constant).
SpaceO(1)Two arrays of 26 counters, whatever the input size.

Only how many of each letter matter, not where they are. Count the letters of chars once into an array have of 26 counters. For each word, take a copy of have and walk the word: subtract one from the counter of each letter. The moment a counter would go below zero, the word asks for more of that letter than chars owns, so it fails. If the walk finishes, the word fits and its length is added. Each letter costs one array update.

  1. Count chars into have[26].
  2. For each word, copy have into left and set ok = true.
  3. For each letter c of the word: decrease left[c]; if it drops below 0, set ok = false and stop.
  4. If ok, add the word's length. Return the total.
class Solution {
    public int countCharacters(String[] words, String chars) {
        int[] have = new int[26];
        for (char c : chars.toCharArray()) have[c - 'a']++;
        int total = 0;
        for (String word : words) {
            int[] left = have.clone();
            boolean ok = true;
            for (char c : word.toCharArray()) {
                if (--left[c - 'a'] < 0) {
                    ok = false;
                    break;
                }
            }
            if (ok) total += word.length();
        }
        return total;
    }
}

Edge cases to test

  • A word longer than chars can never be built, so it can be skipped right away
  • A word that repeats a letter more times than chars has it ("apple" against one p) does not count, even though every letter appears in chars
  • No word fits: the answer is 0
  • Every word is checked on its own: letters used by one word are available again for the next
  • The same word may appear several times in words; each copy counts

Hints

Hint 1

A word fits when, for every letter, the word uses it no more often than chars contains it.

Hint 2

Count the letters of chars once, into an array of 26 counters.

Hint 3

For each word, count its letters too (or subtract from a copy of the chars counts) and stop as soon as some letter runs out.

FAQ

What is the best time complexity for Find Words That Can Be Formed by Characters?

Optimal (letter counts) runs in O(C + W · L) time and O(1) extra space. One pass over chars, then one pass over each word (plus a 26-entry copy per word, which is constant).

Which pattern does Find Words That Can Be Formed by Characters use?

It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.

Is there a brute force solution for Find Words That Can Be Formed by Characters?

Yes. Brute force (cross letters off a copy) takes O(W · L · C) time and O(C) space. Treat chars as a pile of letter tiles.

Which edge cases should I test for Find Words That Can Be Formed by Characters?

A word longer than chars can never be built, so it can be skipped right away; A word that repeats a letter more times than chars has it ("apple" against one p) does not count, even though every letter appears in chars; No word fits: the answer is 0; Every word is checked on its own: letters used by one word are available again for the next; The same word may appear several times in words; each copy counts.