Longest Common Prefix in Python

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        # Step 1: Check if the list is empty
        if not strs:
            return ""

        # Step 2: Find the length of the shortest string
        min_length = min(len(s) for s in strs)

        # Step 3: Iterate over the characters up to the length of the shortest string
        for i in range(min_length):
            # Compare each character with the first string's character
            char = strs[0][i]
            for s in strs:
                if s[i] != char:
                    # Step 4: Return the common prefix found so far
                    return strs[0][:i]

        # If no mismatch was found, return the entire shortest string
        return strs[0][:min_length]

PrevNext