Sponsored
Sponsored
In this approach, we will use a hash map (or dictionary) to store the frequency of each character for each word. We then update a common frequency count table that holds the minimum frequency of each character across all words. This ensures that only characters existing in all words are recorded.
Time Complexity: O(N*K) where N is the number of words and K is the average length of the words. Space Complexity: O(1) since the space does not scale with input size.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5
6std::vector<char> findCommonChars(const std::vector<std::string>& words) {
7 std::vector<int> min_count(26, INT_MAX);
8
9 for(const auto& word : words) {
10 std::vector<int> count(26, 0);
11 for(char c : word) {
12 count[c - 'a']++;
13 }
14 for(int i = 0; i < 26; i++) {
15 min_count[i] = std::min(min_count[i], count[i]);
16 }
17 }
18
19 std::vector<char> result;
20 for(int i = 0; i < 26; i++) {
21 while(min_count[i]-- > 0) {
22 result.push_back(i + 'a');
23 }
24 }
25 return result;
26}
27
28int main() {
29 std::vector<std::string> words = {"bella", "label", "roller"};
30 std::vector<char> result = findCommonChars(words);
31 for(char c : result) {
32 std::cout << c << " ";
33 }
34 return 0;
35}
The C++ solution follows a similar approach to C. We use vectors to hold character counts and find the minimum common count, using these to build the result vector for common characters.
We can alternatively use direct character arrays to represent frequencies and update these arrays with each subsequent word processed. Starting with the first word's character frequencies, we iteratively compute the minimum with the rest.
Time Complexity: O(N*K). Space Complexity: O(1) for constant sized arrays.
1
This Java implementation uses character arrays to count and find the minimum frequency directly. It leverages the fixed size of the character space for efficiency.