Problem statement

https://leetcode.com/problems/longest-common-prefix/

Solution

There is horizontal scanning, vertical scanning, Divide and conquer, Binary search, more general problems of this type can be solved with Trie. Here I use vertical scanning solution.

Complexity

Time complexity is $O(S)$, where $S$ is sum of lengths of all strings, space complexity is $O(m)$, where $m$ is maximal length of string.

Code

class Solution:
    def longestCommonPrefix(self, strs):
        if not strs: return ""
        for i in range(len(strs[0]) + 1):
            if not all(i < len(word) and word[i] == strs[0][i] for word in strs):
                break
                
        return strs[0][:i]