Start with the first word, shrink
Assume the first string is the prefix. For every later word, cut the prefix down until it is a prefix of that word.
The answer can only get shorter. The moment it becomes empty, stop.
Algorithm
- Seed
prefwithstrs[0]. - While the current word does not start with
pref, drop the last character ofpref. - Return
pref.
- Time
- O(n k)
- Space
- O(k)
class Solution: def longestCommonPrefix(self, strs: list[str]) -> str: if not strs: return "" pref = strs[0] for w in strs[1:]: while not w.startswith(pref): pref = pref[:-1] if not pref: return "" return pref