Longest Common Prefix Leetcode Solution Python

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 "".

Leetcode Solution (Python)

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = ''
        # Length of smallest string
        minlen = len(strs[0])
        for string in strs:
            if len(string)<minlen:
                minlen = len(string)
        
        for i in range(0,minlen):
            curr_char = strs[0][i]
            for string in strs:
                if string[i]!=curr_char:
                    return prefix
            prefix += curr_char
        
        return prefix

Elements of Programming Interviews in Python: The Insiders’ Guide

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.