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.


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
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments