Common Alphabets N Strings
Count the number of lowercase alphabets that appear in all given strings
Understand the Problem
Problem Statement
Given N strings, each containing only lowercase alphabets (a-z), determine the count of alphabets that are present in all N strings. An alphabet may appear multiple times in a string, but we only care if it appears at least once in each string.
Constraints
- 2 ≤ N ≤ 500
- 1 ≤ Length of each string ≤ 1000
- Each string contains only lowercase letters a-z
- Alphabets can be repeated within a string
Examples
3
mnppqqr
ajkmnnm
poormanagement2Only alphabets 'm' and 'n' are present in all three strings. String 1 has m,n,p,q,r. String 2 has a,j,k,m,n. String 3 has p,o,r,m,a,n,g,e,t,i. The common alphabets across all three are m and n.
2
abc
def0No alphabets are common between 'abc' and 'def'. Each alphabet appears in only one of the two strings.
4
hello
world
hold
old2Alphabets 'l' and 'o' are present in all four strings. The letter 'h' is missing from 'world', 'e' is missing from 'world' and 'old', etc.
Solution
#include <stdio.h>
#include <string.h>
int main() {
int n;
scanf("%d", &n);
int letterCount[26] = {0}; // Track how many strings contain each letter
for (int i = 0; i < n; i++) {
char s[1001];
scanf("%s", s);
// Track which letters are present in current string
int present[26] = {0};
// Mark each unique letter as present
for (int j = 0; s[j] != '\0'; j++) {
present[s[j] - 'a'] = 1;
}
// Update global count for letters found in this string
for (int k = 0; k < 26; k++) {
if (present[k]) {
letterCount[k]++;
}
}
}
// Count letters present in all strings
int count = 0;
for (int i = 0; i < 26; i++) {
if (letterCount[i] == n) {
count++;
}
}
printf("%d\n", count);
return 0;
}C Solution Explanation:
- Initialize counter array:
letterCount[26]tracks how many strings contain each alphabet - For each string: Create a
present[26]array to track unique letters in current string - Mark letters: Iterate through string characters and set
present[character - 'a'] = 1 - Update global count: For each letter marked as present, increment its count in
letterCount - Count common letters: Letters with count equal to N are present in all strings
Time complexity: O(N × M) where M is average string length. Space complexity: O(1) since arrays are fixed size (26).