Longest Common Prefix – Leetcode Solution

In this post, we are going to solve the 14. Longest Common Prefix problem of Leetcode. This problem 14. Longest Common Prefix is a Leetcode easy level problem. Let’s see code, 14. Longest Common Prefix.

Problem

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.

Constraints

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

Now, let’s see the code of 14. Longest Common Prefix – Leetcode Solution.

Longest Common Prefix – Leetcode Solution

14. Longest Common Prefix – Solution in Java

class Solution {
    public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0)
                return "";

            Arrays.sort(strs);
            String first = strs[0];
            String last = strs[strs.length - 1];
            int c = 0;
            while(c < first.length())
            {
                if (first.charAt(c) == last.charAt(c))
                    c++;
                else
                    break;
            }
            return c == 0 ? "" : first.substring(0, c);
        }
    }

14. Longest Common Prefix – Solution in C++

class Solution {
public:
    string longestCommonPrefix(vector<string>& str) {
        int n = str.size();
        if(n==0) return "";
        
        string ans  = "";
        sort(begin(str), end(str));
        string a = str[0];
        string b = str[n-1];
        
        for(int i=0; i<a.size(); i++){
            if(a[i]==b[i]){
                ans = ans + a[i];
            }
            else{
                break;
            }
        }
        
        return ans;
        
    }
};

14. Longest Common Prefix – Solution in Python

class Solution(object):
     def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ""
            shortest = min(strs,key=len)
            for i, ch in enumerate(shortest):
                for other in strs:
                    if other[i] != ch:
                        return shortest[:i]
            return shortest
        

Note: This problem 14. Longest Common Prefix is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

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