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 character belongs in the answer once for each copy that every word can provide. If one word has three l characters and another has only two, only two copies can be common. Therefore the number of common copies of each letter is the minimum frequency of that letter across all words.
You only need 26 counters because every character is a lowercase English letter. Count one word at a time, and for each letter keep the smallest count seen so far. After all words are processed, a minimum of zero means the letter is absent from at least one word, while a larger minimum tells you exactly how many strings to append.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(S + 26W) | Each input character increments exactly one frequency counter. For each of the W words, the algorithm then checks all 26 letters once, and the final output scan checks those 26 letters once more; no character is rescanned beyond these passes. |
| Space | O(26) = O(1) extra space | Each word uses one 26-entry temporary array and the running minimum uses another, so the working memory stays fixed regardless of input length. The returned result is required output and is excluded; its size can be as large as the shortest word in the worst case. |
#include <algorithm>
#include <climits>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
vector<int> minFreq(26, INT_MAX);
for (const string& word : words) {
vector<int> freq(26, 0);
for (char c : word) {
freq[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
minFreq[i] = min(minFreq[i], freq[i]);
}
}
vector<string> result;
for (int i = 0; i < 26; i++) {
while (minFreq[i]-- > 0) {
result.push_back(string(1, 'a' + i));
}
}
return result;
}
};The fresh freq array inside the word loop is essential: it describes only the current word. The min operation then combines that isolated count with the best count all previous words could guarantee. At the end, the while loop is deliberately not an if statement; a minimum of two means two separate copies must be added to the result.