Longest Common Prefix

Key Idea

Solution

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        # Inputs: List[str]
        # Output: str
        # Descpriont:
            # longest common prefix
        # Example:
            # Inputs: ["flower", "flow", "flight"]
            # Output: "fl"
        # Example:
            # Inputs: ["dog", "racecar", "car"]
            # Output: ""
        
        # Initialize
        prefix_runner = ""
        shortest_str = min(strs, key=len)
        # Iterate through shortest string
        for index in range(len(shortest_str)):
            # Create an indicator for while loop
            indicator = True
            # For each str, check if for same index they are the same character
            for comparing_str in strs:
                if comparing_str[index] != shortest_str[index]:
                    # If not set indicator to false
                    indicator = False
            # Check indicator
            if indicator:
                prefix_runner += shortest_str[index]
            else:
                return prefix_runner
        # If all str are the same comparing to prefix
        return prefix_runner

Complexity