top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Given an array on 'N' names (Strings) , find how many distinct name are there in total?

0 votes
369 views

Given an array on 'N' names (Strings) , find how many distinct name are there in total?
1. Code should have minimum time complexity.
2. Share the C code?

posted May 16, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
/** Header File inclusion */
#include <stdio.h>
#include <stdlib.h>

#define MAX_NAMES 10
#define MAX_NAME_LENGTH 10

/** Main function definition */
int main()
{
        /** Array of pointer which will store all names */
    char *names[MAX_NAMES];
    int n = 0,i=0,j=0,count=0,flag=0;
    printf("\nEnter the No of names ");
    /** Get the no of name count */
    scanf("%d",&n);
    /** Get the names */
    printf("\nEnter the names(max char %d)\n",MAX_NAME_LENGTH);
    for(i=0;i<n;i++) 
    {   
        /** allocate memory for the names */
        names[i] = (char *)malloc(sizeof(char) * MAX_NAME_LENGTH);
        if(!names[i])
            return;
        /** If you enter more than max character then unknown behaviour */
        scanf("%s",names[i]);
    }

    for(i=0;i<n;i++)
    {
        flag = 0;
        if(names[i] != NULL) {

            for(j=i+1;j<n;j++){
                /** Compare the string with next string */
                if(names[j]!=NULL) {
                    if(!strcmp(names[i],names[j])) {
                        /** Make flag set to know string is identical */
                        flag = 1;
                        /** If string is identical then make it as NULL so that next time we will not compare */
                        names[j] = NULL;
                    }
                }
            }
            /** If flag is zero then the string is not matched with any other string */
            if(flag == 0) 
                count++;

        }
    }
    printf("\nCount is %d",count);
}
answer May 16, 2017 by Jaganathan
Similar Questions
0 votes

Given an unordered array A of size n and integer x. What is the best complexity to find two elements in A whose sum is x?
Share the algo, its complexity and if possible C code.

+4 votes

Given a dictionary of strings and another string find out if the string is an exact match to some words in the dictionary or varies at most in only one place of some word of the dictionary?

...