Longest Common Prefix

Find the longest start that every string in an array shares, by comparing the strings one column at a time.

Given an array of strings strs, return the longest string that every one of them starts with. This shared start is called their longest common prefix. If the strings do not all start with the same character, return an empty string.

Example 1
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Example 2
Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: the first letters already differ.
Solution

The Idea

You have probably seen a phone's contact list or a search box narrow down as you type: "fl" still matches flower, flow and flight, but "flo" leaves flight out. The longest common prefix is the most you could type before the three words part ways.

Take Example 1. Read the three words from the left, one letter at a time. All three begin with f. All three have l next. Then flower and flow have o, but flight has i. The shared start ends just before that letter, so the answer is "fl".

Look at the picture below. The words are written one above the other, so letters at the same position line up in a column. Columns are numbered from 0, the same way Java numbers the characters of a string.

The strings flower, flow and flight lined up in columns. Columns 0 and 1 hold f and l in every string, so the common prefix is fl. In column 2 the letters o, o and i differ, so the search stops there.

Columns 0 and 1, in green and labelled "same in all: f, l", hold the same letter in every row. Column 2, in orange, holds o, o and i, which are not all the same, so the answer is the two green columns: "fl". Nothing to the right of column 2 matters, even though flower and flight still have letters there.

What if the words were flow, flower and flowers? Every column of flow would match, and then flow simply runs out of letters. A string that ends is a stop as well: the prefix can never be longer than the shortest string.

So the answer is the run of matching columns from the left, and the search stops at the first column that either has a mismatch or reaches the end of some string.

Solution Approach

Three decisions turn that idea into code: which letter each column is checked against, when to stop, and in what order to make the two stop checks. A second way of scanning, one string at a time, follows as an optional alternative.

The letter each column is checked against

How do we know whether a column holds one letter in every row? Pick one string as the reference, the string every other one is compared with. The first string, strs[0], works as well as any other. For column i, its letter is c, and every other string must have c at position i too.

The reference also limits how far to go. The common prefix is a start of the first string, so the columns never need to run past its last letter.

When to stop

When does the search end? As soon as one string either has no letter in column i, because its length is i, or has a letter other than c. The prefix is then the first i letters of the reference, columns 0 to i - 1.

Stopping at the first bad column is what keeps this cheap. In Example 2, dog, racecar and car already differ in column 0, so the method reads one letter from each word and returns "".

If every column of the reference matches, nothing stopped the search. The whole first string is then a start of all the others, and it is the answer.

The order of the two checks

Does it matter which stop check comes first? It does. charAt(i) throws an exception when the string has no position i. So the length check, whether the string's length equals i, must come first. Java's || skips the right side once the left side is true, so charAt is only called on a string long enough to have column i.

Optional: one string at a time

Another way works row by row instead of column by column. Start with the whole first string as the prefix. Compare it with the second string and cut it down to the part they share, then compare what is left with the third string, and so on. When all the strings are equal, both ways read every character. They differ when the mismatch comes late in the array. For ["flower", "flower", "dog"], the row way compares all six letters of the two flowers before dog cuts the prefix to "". The column way stops in column 0.

Java Solution

The method longestCommonPrefix works in these steps:

  1. First, if strs is empty, return "", since there is no first string to compare with.
  2. Keep the reference string in first. An outer loop moves i over its columns, from 0 up to first.length() - 1, and reads the letter there into c.
  3. Inside, a second loop moves k over the other strings, from 1 to the end of the array. If strs[k] ends at column i, or holds a letter other than c there, return first.substring(0, i).
  4. If the outer loop finishes, every column of first matched, so return first itself.

The main method runs both examples, a second string shorter than the first, a first string that is a start of the others, a single string, an empty first string and an empty array. Each result is printed in quotes, so an empty string shows as "".

Java
public class LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";                                  // no strings, no prefix
        }
        String first = strs[0];
        for (int i = 0; i < first.length(); i++) {      // column i
            char c = first.charAt(i);
            for (int k = 1; k < strs.length; k++) {
                if (i == strs[k].length() || strs[k].charAt(i) != c) {
                    return first.substring(0, i);       // a string ended or disagreed
                }
            }
        }
        return first;                         // the first string is a prefix of all others
    }

    static void show(String... strs) {
        System.out.println("\"" + longestCommonPrefix(strs) + "\"");
    }

    public static void main(String[] args) {
        show("flower", "flow", "flight");
        show("dog", "racecar", "car");
        show("ab", "a");
        show("flow", "flower", "flowers");
        show("alone");
        show("", "abc");
        show();
    }
}

Running it prints:

Output
"fl"
""
"a"
"flow"
"alone"
""
""

"fl" and "" are the answers to Example 1 and Example 2. The third line, "a", comes from ["ab", "a"]. In column 1 the string "a" has run out, so the length check stops the search before charAt(1) is ever called on it.

Swap the two checks, with strs[k].charAt(i) != c first, and the same input throws java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1 instead of returning "a".

The line "flow" is the case where nothing stops the search: every column of flow matches flower and flowers, so the method returns the whole first string. "alone" comes back whole too, because with a single string the inner loop has nothing to compare. The last two lines are empty for different reasons: an empty first string has no columns at all, and an empty array returns at the first check.

The original implementation, LongestCommonPrefix.java, is on GitHub.

Complexity

The work is one letter read from each string for every column checked, and nothing else is stored.

  • Time: O(S), for S characters in all the strings together, because each column reads at most one letter from each string, and no letter is read twice. All of them are read only when the strings are equal.
  • Space: O(1) besides the result. The loops keep two positions, i and k, and one letter, c. The prefix returned is the output.

When the same set of words gets many prefix questions, a trie fits better. It stores the words as a tree of letters, and the common prefix is the path from the top down to the first letter with more than one branch below it.