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) {
            return strs[0];
        int len=strs[0].length();
        StringBuilder builder =new StringBuilder();
        int c=0;
        return builder.toString();

C++ solution

class Solution {
    string longestCommonPrefix(vector<string>& strs) {
        string str = strs[0];
        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[0][i] for x in strs):
                ans = ans + strs[0][i]
        return ans

JavaScript solution

About Nilesh Raut

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.

2 thoughts on “Leet Code : longest common prefix string C++ ,java , Python Solution”

  1. I am currently writing a paper and a bug appeared in the paper. I found what I wanted from your article. Thank you very much. Your article gave me a lot of inspiration. But hope you can explain your point in more detail because I have some questions, thank you.

Leave a Reply