Leetcode Longest Common Prefix problem solution in Python programming

In the Leetcode Longest Common Prefix problem solution in Python 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 Python programming

class Solution(object):
    def longestCommonPrefix(self, strs):
        x=""
        if len(strs)==0:
            return x
    
        strs.sort()
        j=len(strs[0])
        k=0
    
        while k<j:
            pre=strs[0][k]
            if all(y[k]==pre for y in strs):
                x+=pre
                k+=1            
            else:
                break
                        
        return x

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 *