Leetcode 1002. Find Common Characters
Given an array of strings words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.
Assumptions based on typical constraints:
a-z).INT_MAX).#include <vector>
#include <string>
#include <algorithm>
#include <climits>
using namespace std;
vector<string> commonChars(vector<string>& words) {
vector<int> minFreq(26, INT_MAX); // To store the minimum frequency of each character
for (const string& word : words) {
vector<int> freq(26, 0); // Frequency of characters in the current word
for (char c : word) {
freq[c - 'a']++;
}
// Update the minFreq array
for (int i = 0; i < 26; i++) {
minFreq[i] = min(minFreq[i], freq[i]);
}
}
vector<string> result;
// Collect the common characters
for (int i = 0; i < 26; i++) {
for (int j = 0; j < minFreq[i]; j++) {
result.push_back(string(1, 'a' + i));
}
}
return result;
}
Frequency Calculation: O(N * M), where N is the number of strings and M is the maximum length of each string.
Result Collection: O(26 * k), where k is the maximum possible frequency of any character (which is bounded by the string length and number of strings).
Thus, the overall time complexity is effectively O(N * M), dominated by the frequency calculation step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?