Find the longest common prefix among an array of strings. If there is no common prefix, return an empty string "".

  • Input: An array of strings, strs.
  • Output: The longest common prefix string.
  • Constraints:
    • 1 <= strs.length <= 200
    • 0 <= strs[i].length <= 200
    • strs[i] consists of only lowercase English letters.

Example 1:

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

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""

Solution

The most straightforward approach involves iterating through the strings and progressively shortening a candidate prefix.

  • Initialization: Start by assuming the first string in the array is the longest common prefix.
  • Iteration: Iterate through the remaining strings in the array from the second string onwards.
  • Prefix Adjustment: For each string, check if the current prefix is a prefix of the current string.
    • If it is not, repeatedly shorten the prefix from its end by one character until it matches the beginning of the current string, or until prefix becomes empty.
    • If prefix becomes empty at any point, it means there is no common prefix among all strings, so we can immediately return "".
  • Return: After checking all strings, the remaining prefix will be the longest common prefix.
class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        if not strs:
            return ""

        prefix = strs[0]
        for i in range(1, len(strs)):
            current_str = strs[i]
            # While the prefix is not at the beginning of the current string
            while not current_str.startswith(prefix):
                # Shorten the prefix by one character from the end
                prefix = prefix[:-1]
                # If prefix becomes empty, no common prefix exists
                if not prefix:
                    return ""
        return prefix