Leetcode problem 14. Longest Common Prefix (Python)

Question:

I tried to solve the problem (you can read description here: https://leetcode.com/problems/longest-common-prefix/) And the following is code I came up with.
It gives prefix value of the first string in strs list and compares prefix with every string from the list, popping all characters that are not equal.

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = strs[0][0]
        for i in range(len(strs)):
            for j in range(len(prefix)):
                if strs[i][j] != prefix[j]:
                    prefix.pop(prefix[j])
        return prefix

But this code fails in the very first testcase where strs = ["flower","flow","flight"]
Expected output is "fl", while my code returns just "f"
I am struggling to find what is going wrong in my solution. Maybe you can help?

Asked By: childoflogos

||

Answers:

Iterate over the characters in parallel with zip:

strs = ["flower", "flow", "flight"]

n = 0
for chars in zip(*strs):
    if len(set(chars)) > 1:
        break
    n += 1

# length
print(n) # 2

# prefix
print(strs[0][:n]) # fl

Similar approach as a one-liner using itertools.takewhile:

from itertools import takewhile

prefix = ''.join([x[0] for x in takewhile(lambda x: len(set(x)) == 1, zip(*strs))])
Answered By: mozway

Alternatively you could try to use the lib in oscommonprefix:
(it’s available since Python 3.5+)


def longestCommonPrefix(self, strs: List[str]) -> str:
        return os.path.commonprefix(strs)


strs = ["flower","flow","flight"]
print(longestCommonPrefix(strs))
Answered By: Daniel Hao
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.