Find the Longest Common Prefix using Python

The challenge

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

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

The solution in Python

def longestCommonPrefix(self, strs: List[str]) -> str:
    # the return string
    prefix = ''

    # break words into groups using `zip` and `*`
    # ["flower","flow","flight"] becomes:
    # (('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g'))
    for group in zip(*strs):
        # if the characters don't match, then break
        if not all(char==group[0] for char in group):
            break

        # otherwise, grow the prefix
        prefix += group[0]

    # return the prefix
    return prefix
Tags:
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments