Leetcode Longest Common Prefix problem solution in C programming

In the Leetcode Longest Common Prefix problem solution in C programming Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

Leetcode Longest Common Prefix problem solution in C programming

char * longestCommonPrefix(char ** strs, int strsSize){
    
    int min_str = 200;
    int index;
    
    if(strsSize == 0)
        return "";
    
    if(strsSize < 0 || strsSize > 200)
        return NULL;
                            
    //Find the shortest string
    for(int j=0; j<strsSize; j++){
        if(strlen(strs[j]) < min_str){
            min_str = strlen(strs[j]);
            index = j;
        }
    }
                                    
    for(int i=0; i<min_str; i++){
        for(int j=0; j<strsSize; j++){
            if(strs[index][i] != strs[j][i]){
                strs[index][i] = '\0';
                goto ret;
            }
        }
    }
ret:
    return strs[index];
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *