Longest Common Prefix

Pattern: Strings basics and frequency

easy

Compare the strings column by column. The prefix grows while every string has the same character in the current column, and stops at the first column where one ends or differs.

The problem

Given an array of strings, return the longest string that is a prefix of all of them, or an empty string if they share none. For example, ["flower", "flow", "flight"] gives "fl", and ["dog", "racecar", "car"] gives "".

The function name longestCommonPrefix matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Can the common prefix be longer than the shortest string?
  • Checking one column at a time, when must you stop?
  • Which string can you use as a guide?

Hints

    Brute force, and why it fails

    Try every prefix of the first string, longest first, and test it against all strings: O(L² × n). Column by column stops at the first failure, O(L × n) where L is the answer's length plus one.

    The key insight

    A common prefix is built one column at a time, and the first column that disagrees ends it for good. So one scan down the columns is enough.

    Dry run

    flower0 
    flow1 
    flight2 
    column0

    strs = flower, flow, flight. Use the first word as the guide and check each column.

    Step 1 of 4

    The plan

    first = strs[0]
    for i from 0 to len(first) - 1:
        for each s in strs:
            if i == len(s) or s[i] != first[i]: return first[0 .. i - 1]
    return first
    

    Complexity

    Time
    O(S)
    Space
    O(1)

    S is the total number of characters. Each character is compared at most once, and nothing extra is stored apart from the answer.

    Edge cases

    • One string: it is its own prefix.
    • An empty string in the list: the answer is "".
    • One string is a prefix of another, as in ["ab", "a"]: "a".
    I've built my logic, show the code

    Java

    class Solution {
        public String longestCommonPrefix(String[] strs) {
            String first = strs[0];
            for (int i = 0; i < first.length(); i++) {             // column by column
                char c = first.charAt(i);
                for (String s : strs) {
                    if (i == s.length() || s.charAt(i) != c) return first.substring(0, i);   // a word ends or differs
                }
            }
            return first;
        }
    }

    C++

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            const string& first = strs[0];
            for (size_t i = 0; i < first.size(); i++) {            // column by column
                for (const string& s : strs) {
                    if (i == s.size() || s[i] != first[i]) return first.substr(0, i);   // a word ends or differs
                }
            }
            return first;
        }
    };

    Python

    class Solution:
        def longestCommonPrefix(self, strs: list[str]) -> str:
            first = strs[0]
            for i, c in enumerate(first):           # column by column
                for s in strs:
                    if i == len(s) or s[i] != c:
                        return first[:i]            # a word ends or differs
            return first

    Common mistakes

    • Reading past the end of a shorter string.
    • Returning the shortest string without checking that it matches.
    • Building the prefix with repeated string concatenation.

    Similar problems