Taro Logo

Longest Common Prefix

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+37
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.4K 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 "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty?
  2. Can the strings in the array contain uppercase letters, special characters, or spaces, or are they strictly lowercase English letters?
  3. What is the maximum expected number of strings in the array and the maximum length of an individual string?
  4. Could the array contain duplicate strings, and does that impact the matching logic?
  5. If there are no common characters at all among the strings, should we return an empty string or null?

Brute Force Solution

Approach

Imagine you are holding a group of words and you want to find the longest starting piece that is identical across every single word. The brute force strategy involves testing every possible length of the words, starting from the very beginning letter, and comparing them across all the words one by one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at just the very first letter of the first word.
  2. Check if that exact letter is also the first letter of the second word, the third word, and so on for every single word in your group.
  3. If every single word shares that first letter, add it to your matching list and move on to checking the second letter.
  4. Repeat the process for the second letter, checking it against every word in the group to make sure everyone matches.
  5. Keep checking letter by letter, moving further down the words, as long as every single word still matches.
  6. The moment you find a letter where at least one word does not match, stop your search immediately.
  7. Whatever matching pieces you successfully collected up to that point is your final answer.

Code Implementation

def longest_common_prefix(word_list):
    # Handle edge case where the provided word list is completely empty
    if not word_list:
        return ""

    prefix_length = 0
    first_word = word_list[0]

    while prefix_length < len(first_word):
        current_char = first_word[prefix_length]

        for other_word in word_list:
            # Stop early if we exceed bounds or find a mismatch across words
            if prefix_length >= len(other_word) or other_word[prefix_length] != current_char:
                return first_word[:prefix_length]

        prefix_length += 1

    # Return the entire first word if it is a prefix of all others
    return first_word

Big(O) Analysis

Time Complexity
O(S) – To analyze the time complexity, let n be the number of strings in the array and m be the length of the shortest string. The outer loop iterates through each character position from index 0 up to m, representing the length of the prefix. Inside this outer loop, the inner comparison checks all n strings to see if they match at the current character index. This results in checking up to n strings for each of the m character positions, leading to approximately n times m total operations. Therefore, simplifying this total number of operations based on the total number of characters S across all strings gives a time complexity of O(S).
Space Complexity
O(1) – The algorithm only uses a few primitive pointer variables to track the current character index and word position during the scan. It does not allocate any dynamic data structures, temporary lists, or recursive calls that grow with the input. Therefore, the extra memory remains strictly constant regardless of the number of words or their lengths. This constant auxiliary space usage translates to an optimal O(1) space complexity.

Optimal Solution

Approach

To find the longest shared starting piece among a group of words, the best strategy is to pick a reference word and compare it against the others one character at a time. As soon as you find a mismatch or run out of letters in any word, you know the shared beginning cannot grow any further.

Here's how the algorithm would work step-by-step:

  1. Choose the first word in the group to act as your baseline for comparison.
  2. Look at the first letter of your baseline and check if every other word in the group also starts with that exact same letter.
  3. If all words match, move on to check the second letter of your baseline against all the other words.
  4. Continue this process letter by letter, moving further into the words.
  5. The moment you encounter a word that does not have the current letter, or if you reach the end of any word, stop immediately.
  6. Whatever sequence of letters you successfully matched up to that point is your final answer.

Code Implementation

def longest_common_prefix(string_collection):
    if not string_collection:
        return ""

    # We establish a baseline using the first word to compare characters against all other words.
    baseline_word = string_collection[0]

    for char_index, current_character in enumerate(baseline_word):
        # We iterate through the remaining words to ensure every word shares the exact same prefix sequence.
        for other_word in string_collection[1:]:
            if char_index >= len(other_word) or other_word[char_index] != current_character:
                return baseline_word[:char_index]

    # If the baseline word itself is fully matched across all elements, it is the longest prefix.
    return baseline_word

Big(O) Analysis

Time Complexity
O(S) – To analyze the time complexity, let n be the number of strings in the array and m be the length of the baseline reference word. The outer loop iterates through each character position of the baseline word up to m times. Inside this loop, the algorithm checks that same character against all n minus 1 other strings in the array. This requires performing up to n minus 1 comparisons for each of the m character positions. Therefore, the total number of operations approximates m times n, which simplifies to the Big O time complexity of O(S), where S is the sum of all characters across all strings in the input.
Space Complexity
O(1) – To solve this problem, we only allocate a few primitive variables, such as loop counters and index pointers, to track our position in the baseline word and the other words. These variables take up a constant amount of extra memory regardless of the input size. No auxiliary data structures like temporary lists or hash maps are created during the comparison process. Therefore, the auxiliary space complexity remains constant, perfectly matching Big O notation as O(1).

Edge Cases

Empty array of strings provided as input
How to Handle:
Return an empty string immediately since no strings exist to share a common prefix.
Array containing a single string
How to Handle:
Return that single string itself as it is trivially the longest common prefix.
One string in the array is completely empty
How to Handle:
Return an empty string since the intersection with an empty string yields no common prefix.
All strings in the array are identical
How to Handle:
Return the first string in its entirety since it matches all other elements.
No common prefix exists among any of the strings
How to Handle:
Return an empty string as the comparison terminates at the very first character mismatch.
One string is a strict prefix of another string
How to Handle:
The algorithm correctly stops at the length of the shorter string and returns it.
Strings have vastly different lengths
How to Handle:
Bound the comparison loops by the length of the shortest string to prevent out of bounds errors.
Large array with thousands of long strings
How to Handle:
Ensure linear time complexity with respect to total characters to scale efficiently without memory overhead.
0/75 completed