Find the Longest Common Prefix using Python

0 min read 171 words

The challenge

Write a function to find the longest common prefix string amongst an array of strings. This string manipulation challenge requires careful handling of arrays, similar to getting the last element of a list in Python .

If there is no common prefix, return an empty string "". For more Python string challenges, you might also be interested in converting to PigLatin .

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags