14. Longest Common Prefix

Easy

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

😇 Solution

#Horizontal Scanning

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) == 0:
            return ""
        
        prefix = strs[0]
        
        for i in range(1,len(strs)): #O(n)
            while(strs[i].find(prefix) != 0): #O(S)
                prefix = prefix[0:len(prefix)-1]
            
            if len(prefix) == 0:
                return ""
        
        return prefix
        

Last updated

Was this helpful?