This page looks best with JavaScript enabled

Longest Common Prefix

 ·  ☕ 2 min read  ·  ✍️ Syed Dawood

Problem

LeetCode 14: Longest Common Prefix

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        result = ""
        for chars in zip(*strs):
            if len(set(chars)) > 1:
                return result
            result += chars[0]
        return result

    def longestCommonPrefix2(self, strs: list[str]) -> str:
        if not strs:
            return ""
        max_prefix_len = min(map(len, strs))
        for i in range(max_prefix_len):
            char = strs[0][i]
            if any(s[i] != char for s in strs[1:]):
                return strs[0][:i]
        return strs[0][:max_prefix_len]

Explaination

I know 3 possible solutions for this problem. You can solve using zip and set. if all characters at a position are same then set length is 1.

Next solution is more redimentry, We find out minimum length string, this is the max length of you prefix.Iterate upto the max prefix length, starting from zero. Compare if characters match at that position in all string.

last solution is using Trie with single-child paths. I will come back later and learn it. Hopefully

References

Also see

Share on

ALLSYED
WRITTEN BY
Syed Dawood
< frontend | backend | fullstack > Developer