Search code examples
cstringstrchr

Why this program doesn't give right result when used with large strings?


This program takes an input of number of strings followed by the actual strings. The output should be the number of common characters to all strings.

The constraints are:

  1. No of strings <= 100
  2. Length of string <= 100

For example..

Input:

3 abc bcd cde

Output:

1

As only c is common to all strings.

It gives right output when used with small inputs.

But when used with large strings like this :https://hr-testcases.s3.amazonaws.com/2223/input19.txt?AWSAccessKeyId=AKIAINGOTNJCTGAUP7NA&Expires=1408959130&Signature=E%2BMnR6MA0gQNkuWHMvc70eCL5Dw%3D&response-content-type=text%2Fplain

It gives wrong output of 58 instead of 19.

This is my code :

#include<stdio.h>
#include<string.h> 

void main(){
    int n,i,j,count=0;
    char s[100][100];
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%s",s[i]);
    }
    int t;
    int l = strlen(s[0]);
    for(i=0;i<l;i++){
        t=0;
        for(j=1;j<n;j++){
            if(strchr(s[j],s[0][i])!='\0'){
                t++;
            }
        }
        if(t==n-1)
            count++;
    }
    printf("%d",count);
}

Solution

  • As you iterate over the first string's characters, you might potentially find the same character more than one time.

    This means that common chars found more than one time in the first string will be counted more than one time.

    This is what causing your program to calculate 58 instead of 19.

    Check below some quick update to your program - it treats the duplicates in the first string.

    This program calculates 19 on your 100 strings' test case.

    #include<stdio.h>
    #include<string.h> 
    
    void main(){
        int n,i,j/*,count=0*/;
        int count[26] = {0};  /* counter per char */
        char s[100][101];
        scanf("%d",&n);
        for(i=0;i<n;i++){
            scanf("%s",s[i]);
        }
        int t;
        int l = strlen(s[0]);
        for(i=0;i<l;i++){
            t=0;
    
            /* convert char to integer - assuming lowercase char only */             
            int char_index = s[0][i] - 'a'; 
    
            for(j=1;j<n;j++){
                if(strchr(s[j],s[0][i])!='\0' && count[char_index] == 0){
                    t++;
                }
            }
            if(t==n-1)
                count[char_index] = 1;
                /* count++; */
        }
        /* count how many chars are 1*/
        int count_n = 0;
        int index;
        for (index = 0; index < 26; index ++)
        {
            if (count[index] == 1)
                count_n ++;
        }
        printf("\n\n%d",count_n);
    }