Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A word can be formed exactly when chars contains enough copies of every letter in that word. The order does not matter: using one copy of a means only the number of remaining copies matters, not where that a appeared in chars.
Count each lowercase letter in chars. Then inspect each word independently, consuming one count whenever its letter appears. If any count would become negative, the word needs more copies of that letter than chars provides, so the word is not good. A successful word contributes its full length to the answer.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(m + S) | Building the source inventory reads each character of chars once. Across all words, each character is decremented at most once before a failing word stops early, so the total inspected input is no more than m + S. |
| Space | O(1) extra | The source and temporary arrays each contain 26 integers, a fixed alphabet-sized amount of working memory. The returned integer is not output storage, and there is no degradation for any input shape because the alphabet size stays fixed. |
#include <cstring>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
int cnt[26] = {0};
for (char c : chars) {
cnt[c - 'a']++;
}
int ans = 0;
for (string& w : words) {
int tmp[26];
memcpy(tmp, cnt, sizeof(tmp));
bool ok = true;
for (char c : w) {
if (--tmp[c - 'a'] < 0) {
ok = false;
break;
}
}
if (ok) {
ans += static_cast<int>(w.size());
}
}
return ans;
}
};The decrement and check belong together. For a character c, decreasing tmp[c - 'a'] records that one copy has been used, while checking for a negative result detects the first shortage immediately. Breaking at that point is safe because the word is already impossible; the remaining letters cannot make it valid again.