LeetCode #14: Longest Common Prefix
Given an array of strings, find the longest common prefix shared by all strings.
Example:["flower", "flow", "flight"] → "fl"
Approach: Use the first string as a reference. For each character position, check if ALL strings have that same character.
💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥
Complexity: Time O(S) where S is sum of all characters, Space O(1)
def longestCommonPrefix(strs):
if not strs:
return ""
for i in range(len(strs[0])):
char = strs[0][i]
for s in strs[1:]:
if i >= len(s) or s[i] != char:
return strs[0][:i]
return strs[0]
longestCommonPrefix(["flower","flow","flight"])
fl
longestCommonPrefix(["dog","racecar","car"])
longestCommonPrefix(["interspecies","interstellar","interstate"])
inters