# Leet Code : longest common prefix string C++ ,java , Python Solution

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

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

## Java Solution

``````class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==1)
return strs;
Arrays.sort(strs);
int len=strs.length();

StringBuilder builder =new StringBuilder();

int c=0;
while(c<len){
if(strs.charAt(c)==strs[strs.length-1].charAt(c)){
builder.append(strs.charAt(c));
}
else{
break;
}
c++;
}
return builder.toString();
}
}``````

## C++ solution

``````class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string str = strs;
string finl="";

for(int i = 0; i < str.size(); i++)
{
char currentChar = str[i];
for(int j = 1; j < strs.size(); j++)
{
if(strs[j][i] != currentChar){
return finl;
}

}
finl += currentChar;
}
return finl;
}
};``````

## Python Solution :

``````class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ''
n = len(min(strs))
for i in range(n):
if all(x[i]==strs[i] for x in strs):
ans = ans + strs[i]
else:
break
return ans``````

## JavaScript solution I am Nilesh,3+ years Exp of SEO, content writing, and keyword research. Also rocks it as a software dev with skills in OS, web dev, Flask, Python, C++, data structures, and algorithms. 3 on Leetcode, 5*on Hackerrank more platform.
1. 2. 