---
# System prepended metadata

title: '[14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)'
tags: [easy, String, leetcode]

---

###### tags: `leetcode` `easy` `String`
# [14. Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/)

## Description

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 `""`.  

## Examples
### Example 1:

**Input**: strs = ["flower","flow","flight"]  
**Output**: "fl"  

### Example 2:

**Input**: strs = ["dog","racecar","car"]  
**Output**: ""  
**Explanation**: There is no common prefix among the input strings.  


## Constraints:

- $1 \leq strs.length \leq 200$  
- $0 \leq strs[i].length \leq 200$  
- strs[i] consists of only lowercase English letters.  

## Code

```c=
char* longestCommonPrefix(char** strs, int strsSize) {
    char compareChar;
    char *returnChar, *newPtr;
    // size of char and size of char pointer is different
    returnChar = (char*)malloc(sizeof(char));
    // initialize memory for empty prefix return
    memset(returnChar, '\0', sizeof(char));
    for (int charIndex = 0; strs[0][charIndex] != '\0'; charIndex++) {
        // take character of the first string as comparing sample
        strncpy(&compareChar, &strs[0][charIndex], 1);
        for (int strIndex = 1; strIndex < strsSize; strIndex++) {
            // compare character of the same position, if any not comparison go
            // to the end
            if (compareChar != strs[strIndex][charIndex]) {
                goto end;
            }
        }
        // allocate 2 new memory space for new prefix and '\0'
        returnChar = realloc(returnChar, ((charIndex + 2) * sizeof(char)));
        strncpy(returnChar + charIndex, &compareChar, 1);
        strncpy(returnChar + charIndex + 1, "\0", 1);
    }
end:
    return returnChar;
}
```

## Complexity

|Space |Time  |
|-     |-     |
|$O(N)$|$O(N)$|

## Result

- Runtime : 5 ms, 43.46 % of c submissions  
- Memory usage : 6.2 MB, 6.92 % of c submissions  