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
Example 1
Output: "fl"
Example 2
Output: ""
Explanation: the first letters already differ.
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.
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]icci
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 iicii - 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)ii||charAti
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
- First, if
is empty, returnstrs , since there is no first string to compare with."" - Keep the reference string in
. An outer loop movesfirst over its columns, from 0 up toi , and reads the letter there intofirst.length() - 1 .c - Inside, a second loop moves
over the other strings, from 1 to the end of the array. Ifk ends at columnstrs[k] , or holds a letter other thani there, returnc .first.substring(0, i) - If the outer loop finishes, every column of
matched, so returnfirst itself.first
The main""
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:
"fl"
""
"a"
"flow"
"alone"
""
""
"fl""""a"["ab", "a"]"a"charAt(1)
Swap the two checks, with strs[k].charAt(i) != cjava.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1"a"
The line "flow""alone"
The original implementation,
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,
andi , and one letter,k . The prefix returned is the output.c
When the same set of words gets many prefix questions, a