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 <stdio.h>
2#include <string.h>
3#include <stdbool.h>
4
5void findCommonChars(char** words, int wordsSize) {
6 int count[wordsSize][26];
7 int minCount[26];
8 bool first = true;
9
10 for (int i = 0; i < wordsSize; i++) {
11 memset(count[i], 0, 26 * sizeof(int));
12 for (int j = 0; words[i][j] != '\0'; j++) {
13 count[i][words[i][j] - 'a']++;
14 }
15 }
16
17 memset(minCount, 0x7f, 26 * sizeof(int)); // 0x7f is safe for int
18 for (int i = 0; i < 26; i++) {
19 if (!first) {
20 for (int j = 0; j < wordsSize; j++) {
21 if (count[j][i] < minCount[i]) {
22 minCount[i] = count[j][i];
23 }
24 }
25 } else {
26 for (int j = 0; j < wordsSize; j++) {
27 minCount[i] = count[j][i] < minCount[i] ? count[j][i] : minCount[i];
28 }
29 first = false;
30 }
31 }
32
33 for (int i = 0; i < 26; i++) {
34 for (int j = 0; j < minCount[i]; j++) {
35 printf("%c ", i + 'a');
36 }
37 }
38 printf("\n");
39}
40
41int main() {
42 char* words[] = {"bella", "label", "roller"};
43 findCommonChars(words, 3);
44 return 0;
45}
This C solution initializes two arrays of size 26 (for each letter of the alphabet) to count occurrences. It iterates over each word, updates character counts, and then calculates the minimum count for each character.
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#
In this C implementation, we use frequency arrays to compute the minimum occurrence of each character across all words. Frequency is updated per word using a temporary array and merged via a minimum operation.