We take the first string as our initial prefix and repeatedly prune it from the end whenever it doesn't match the start of the next string in the array.
- If
strsis empty, return "". - Set
prefix = strs[0]. - For each string
sinstrs[1:]:- While
sdoes not start withprefix:- Shorten
prefixby removing the last character. - If
prefixbecomes empty, return "".
- Shorten
- While
- Return
prefix.
- Time Complexity: O(S), where S is the sum of all characters in all strings.
- Space Complexity: O(1).
def longest_common_prefix(strs):
if not strs: return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix: return ""
return prefix