Find the longest common prefix among an array of strings. If there is no common prefix, return an empty string "".
- Input: An array of strings,
strs. - Output: The longest common prefix string.
- Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]consists of only lowercase English letters.
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Solution
The most straightforward approach involves iterating through the strings and progressively shortening a candidate prefix.
- Initialization: Start by assuming the first string in the array is the longest common prefix.
- Iteration: Iterate through the remaining strings in the array from the second string onwards.
- Prefix Adjustment: For each string, check if the current
prefixis a prefix of the current string.- If it is not, repeatedly shorten the
prefixfrom its end by one character until it matches the beginning of the current string, or untilprefixbecomes empty. - If
prefixbecomes empty at any point, it means there is no common prefix among all strings, so we can immediately return"".
- If it is not, repeatedly shorten the
- Return: After checking all strings, the remaining
prefixwill be the longest common prefix.
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]
# While the prefix is not at the beginning of the current string
while not current_str.startswith(prefix):
# Shorten the prefix by one character from the end
prefix = prefix[:-1]
# If prefix becomes empty, no common prefix exists
if not prefix:
return ""
return prefix