Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string.
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters
strs = ["flower","flow","flight"]"fl"strs = ["dog","racecar","car"]""strs = ["interview","internal","interpret"]"inter"Finding the longest common prefix means identifying the longest string that all words in an array share at their very beginning. The moment any single word diverges from the others, the shared prefix ends.
We find the common prefix between the first two words. We then compare that result with the third word, then the fourth, and so on. If at any point the prefix becomes empty, we can stop early.
if not strs: return ""
prefix = strs[0]
for i in range(1, len(strs)):
while not strs[i].startswith(prefix):
prefix = prefix[:-1]
if not prefix: return ""
return prefixThe horizontal scan might compare many characters multiple times across strings. The core insight is to look at the words column-by-column. We pick the first word as a guide and check the same position in every other word simultaneously. This allows us to find the exact character where the agreement breaks.
We iterate through the characters of the first word. For each position, we check if all other strings have the same character. If a string is too short or has a different character, we return the prefix found so far.
if not strs: return ""
for i in range(len(strs[0])):
char = strs[0][i]
for j in range(1, len(strs)):
# If word is too short or character doesn't match
if i == len(strs[j]) or strs[j][i] != char:
return strs[0][:i]
return strs[0]Vertical Scanning
Column 0: reference character is 'F' from "FLOWER".