Taro Logo

Longest Common Prefix

Easy
Amazon logo
Amazon
3 views
Topics:
ArraysStrings

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.

Solution


Longest Common Prefix

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.

Brute Force Solution

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:

  1. If the input array is empty, return an empty string.
  2. Iterate through the characters of the first string.
  3. For each character, check if it is the same in all other strings at the same index.
  4. If a mismatch is found, return the prefix of the first string up to the current index.
  5. If all characters of the first string match the corresponding characters in all other strings, the first string is the longest common prefix.

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.

Optimal Solution

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:

  1. If the input array is empty, return an empty string.
  2. Initialize the prefix with the first string in the array.
  3. Iterate through the rest of the strings in the array.
  4. For each string, keep shortening the prefix until it is a prefix of the current string.
  5. Return the final prefix.

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.

Edge Cases

  • Empty input array: Return "".
  • Array with only one string: Return the string itself.
  • No common prefix: Return "".
  • Strings with different lengths: The loop must check if the index is within the bounds of all strings.