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 "".
For example:
Input: strs = ["flower","flow","flight"] Output: "fl"
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters if it is non-empty.
This problem asks us to find the longest common prefix string amongst an array of strings. If no common prefix exists, return an empty string.
A brute-force approach involves iterating through the characters of the first string and comparing them with the characters at the same index in all other strings. If a mismatch is found, we return the prefix found so far. If we reach the end of the first string, that string itself is the longest common prefix.
Algorithm:
Code (Python):
def longestCommonPrefix_brute_force(strs):
if not strs:
return ""
first_str = strs[0]
for i in range(len(first_str)):
char = first_str[i]
for j in range(1, len(strs)):
if i >= len(strs[j]) or strs[j][i] != char:
return first_str[:i]
return first_str
Time Complexity: O(S), where S is the total number of characters in all strings. In the worst case, we might have to compare each character of each string.
Space Complexity: O(1), as we are only using a constant amount of extra space.
A more efficient approach is to use a divide-and-conquer strategy. The idea is to recursively find the longest common prefix of the first half and the second half of the input array, and then find the longest common prefix of those two prefixes.
Another optimal solution is to use horizontal scanning.
Algorithm:
Code (Python):
def longestCommonPrefix(strs):
if not strs:
return ""
prefix = strs[0]
for i in range(1, len(strs)):
while strs[i].find(prefix) != 0:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
Time Complexity: O(S), where S is the total number of characters in all strings. In the worst case, we might have to iterate through all characters of all strings.
Space Complexity: O(1), as we are only using a constant amount of extra space.