SDE & MLE Prep

14. Longest Common Prefix

Problem

Return the longest string that is a prefix of every string in strs, or "" if they share no common prefix.

Example: ["flower","flow","flight"] → "fl"; ["dog","racecar","car"] → ""

Vertical scan: compare column i of every string with the first string; stop at the first mismatch or end of any string.

Complexity: O(total characters).

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        first = strs[0]
        for i, ch in enumerate(first):
            for s in strs[1:]:
                if i == len(s) or s[i] != ch:
                    return first[:i]
        return first