Find Words That Can Be Formed by Characters
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 <= 10001 <= words[i].length, chars.length <= 100words[i]andcharscontain 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Brute force (cross letters off a copy) | O(W · L · C) | O(C) |
| Sort and match | O(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)
O(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.O(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.
- Set total = 0.
- For each word, copy chars into a mutable pile.
- For each letter of the word, look for it in the pile. If it is missing, the word fails; otherwise remove that one tile.
- 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;
}
}class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
total = 0
for word in words:
pile = list(chars)
ok = True
for c in word:
if c not in pile:
ok = False
break
pile.remove(c)
if ok:
total += len(word)
return totalclass Solution {
public:
int countCharacters(vector<string>& words, string chars) {
int total = 0;
for (const string& word : words) {
string pile = chars;
bool ok = true;
for (char c : word) {
size_t at = pile.find(c);
if (at == string::npos) {
ok = false;
break;
}
pile.erase(at, 1);
}
if (ok) total += word.size();
}
return total;
}
};function countCharacters(words, chars) {
let total = 0;
for (const word of words) {
const pile = chars.split('');
let ok = true;
for (const c of word) {
const at = pile.indexOf(c);
if (at < 0) {
ok = false;
break;
}
pile.splice(at, 1);
}
if (ok) total += word.length;
}
return total;
}2Sort and match
O(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.O(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.
- Sort chars into an array pool.
- For each word: sort its letters, then set i = 0 (in the word) and walk j over pool.
- When pool[j] equals word[i], advance i. Stop once i reaches the word's length.
- 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;
}
}class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
pool = sorted(chars)
total = 0
for word in words:
w = sorted(word)
i = 0
for ch in pool:
if i == len(w):
break
if ch == w[i]:
i += 1
if i == len(w):
total += len(w)
return totalclass Solution {
public:
int countCharacters(vector<string>& words, string chars) {
string pool = chars;
sort(pool.begin(), pool.end());
int total = 0;
for (const string& word : words) {
string w = word;
sort(w.begin(), w.end());
size_t i = 0;
for (size_t j = 0; j < pool.size() && i < w.size(); j++) {
if (pool[j] == w[i]) i++;
}
if (i == w.size()) total += w.size();
}
return total;
}
};function countCharacters(words, chars) {
const pool = chars.split('').sort();
let total = 0;
for (const word of words) {
const w = word.split('').sort();
let i = 0;
for (let 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)
O(C + W · L)One pass over chars, then one pass over each word (plus a 26-entry copy per word, which is constant).O(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.
- Count chars into have[26].
- For each word, copy have into left and set ok = true.
- For each letter c of the word: decrease left[c]; if it drops below 0, set ok = false and stop.
- 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;
}
}class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
have = [0] * 26
for c in chars:
have[ord(c) - 97] += 1
total = 0
for word in words:
left = have[:]
ok = True
for c in word:
left[ord(c) - 97] -= 1
if left[ord(c) - 97] < 0:
ok = False
break
if ok:
total += len(word)
return totalclass Solution {
public:
int countCharacters(vector<string>& words, string chars) {
int have[26] = {0};
for (char c : chars) have[c - 'a']++;
int total = 0;
for (const string& word : words) {
int left[26];
for (int k = 0; k < 26; k++) left[k] = have[k];
bool ok = true;
for (char c : word) {
if (--left[c - 'a'] < 0) {
ok = false;
break;
}
}
if (ok) total += word.size();
}
return total;
}
};function countCharacters(words, chars) {
const have = new Array(26).fill(0);
for (const c of chars) have[c.charCodeAt(0) - 97]++;
let total = 0;
for (const word of words) {
const left = have.slice();
let ok = true;
for (const c of word) {
if (--left[c.charCodeAt(0) - 97] < 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.