medium
1 views

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

Example 1
Input
3
mnppqqr
ajkmnnm
poormanagement
Output
2
Explanation

Only 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.

Example 2
Input
2
abc
def
Output
0
Explanation

No alphabets are common between 'abc' and 'def'. Each alphabet appears in only one of the two strings.

Example 3
Input
4
hello
world
hold
old
Output
2
Explanation

Alphabets '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;
}
Time:O(N × M) where N is number of strings and M is average string length
Space:O(1) - fixed size arrays of 26 elements each
Approach:

C Solution Explanation:

  1. Initialize counter array: letterCount[26] tracks how many strings contain each alphabet
  2. For each string: Create a present[26] array to track unique letters in current string
  3. Mark letters: Iterate through string characters and set present[character - 'a'] = 1
  4. Update global count: For each letter marked as present, increment its count in letterCount
  5. 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).

Visual Explanation

Loading diagram...