← switch

14. Longest Common Prefix

easy

Array · String · Trie

read the problem on leetcode →

first solved 15 Aug 2024 · 2 accepted submissions

python
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        first = strs[0]

        for i in range(len(first)):
            char = first[i]

            for s in strs[1:]:
                if i >= len(s) or s[i] != char:
                    return first[:i]

        return first
python
class Solution:
    def longestCommonPrefix(self, v: List[str]) -> str:
        ans=""
        v=sorted(v)
        first=v[0]
        last=v[-1]
        for i in range(min(len(first),len(last))):
            if(first[i]!=last[i]):
                return ans
            ans+=first[i]
        return ans