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 "".
- All given inputs are lowercase English letters
a-z. - The number of strings
nwill be between 0 and 200. - The length of each string will be between 0 and 200.
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Solution
To find the longest common prefix, we can compare characters at the same index across all strings.
- Initialize the
prefixwith the first string in the array. If the array is empty, return"". - Iterate through the rest of the strings in the array, starting from the second string.
- For each string, compare its characters with the current
prefixcharacter by character. - If a character mismatch is found or the current string is shorter than the
prefix, truncate theprefixto the matched length. - If at any point the
prefixbecomes empty, we can stop and return"", as no common prefix exists. - After checking all strings, the remaining
prefixis the longest common prefix.
Code (Python):
class Solution:
def longestCommonPrefix(self, strs: list[str]) -> str:
if not strs:
return ""
prefix = strs[0]
for i in range(1, len(strs)):
current_str = strs[i]
j = 0
while j < len(prefix) and j < len(current_str) and prefix[j] == current_str[j]:
j += 1
prefix = prefix[:j] # Truncate prefix to the matched length
if not prefix: # If prefix becomes empty, no common prefix exists
break
return prefix
