LeetCode 14: Longest Common Prefix

link

At an index, if all strings have the same character, set of these characters will have length one.

Say there are n strings and the shortest string has length k. There are k iterations. In each iteration both collecting characters at a given index and creating the set takes time n.

Time: \mathcal{O}(n \cdot k), space: \mathcal{O}(n).

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        common_prefix = []
        for heads in zip(*strs):
            if len(set(heads)) != 1:
                break
            common_prefix.append(heads[0])

        return "".join(common_prefix)

Leave a comment