Longest Common Prefix
Longest Common Prefix is a easy arrays & hashing problem solved with the string basics pattern.
The best approach, optimal (vertical scanning), runs in O(n · m) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (shrink a candidate prefix) up.
Problem
You are given an array of lowercase words strs. Return the longest string that is a prefix of every word in the array.
If the words share no common beginning, return the empty string "".
Examples
Example 1
- Input
strs = ["interview", "internet", "interval"]- Output
"inter"- Why
- All three words begin with "inter"; the next letters v, n and v are not all equal.
Example 2
- Input
strs = ["apple", "banana", "apricot"]- Output
""- Why
- "banana" starts with b while the others start with a, so no prefix is shared.
Example 3
- Input
strs = ["stack", "stack", "stackoverflow"]- Output
"stack"- Why
- The shortest word is itself the common prefix.
Constraints
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]contains only lowercase English letters
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (shrink a candidate prefix) | O(n · m + m²) | O(m) |
| Optimal (vertical scanning) | O(n · m) | O(1) |
1Brute force (shrink a candidate prefix)
O(n · m + m²)m is the length of the first word. Each word needs one successful check of up to m characters, and the candidate shrinks at most m times in total, each failed check costing up to m.O(m)The candidate prefix string.Take the first word as the candidate. For every other word, chop characters off the end of the candidate until the word starts with it. Whatever survives all words is the answer.
- Set prefix = strs[0].
- For each next word, while it does not start with prefix, remove the last character of prefix.
- If prefix becomes empty, return it early.
- Return prefix.
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
}
if (prefix.isEmpty()) return "";
}
return prefix;
}
}class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
prefix = strs[0]
for word in strs[1:]:
while not word.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefixclass Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = strs[0];
for (int i = 1; i < (int)strs.size(); i++) {
while (strs[i].compare(0, prefix.size(), prefix) != 0) {
prefix.pop_back();
}
if (prefix.empty()) return "";
}
return prefix;
}
};function longestCommonPrefix(strs) {
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.slice(0, -1);
}
if (prefix === "") return "";
}
return prefix;
}2Optimal (vertical scanning)
O(n · m)n words times m, the length of the answer plus one; it never reads past the first mismatch.O(1)No extra storage besides the returned substring.Check column by column. For position i, compare character i of the first word with character i of every other word. The first time some word is too short or has a different character, the prefix ends just before i.
- For i from 0 to strs[0].length - 1, let c = strs[0][i].
- For every other word, if i == word.length or word[i] != c, return strs[0].substring(0, i).
- If the loop finishes, the whole first word is the prefix.
class Solution {
public String longestCommonPrefix(String[] strs) {
String first = strs[0];
for (int i = 0; i < first.length(); i++) {
char c = first.charAt(i);
for (int j = 1; j < strs.length; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return first.substring(0, i);
}
}
}
return first;
}
}class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
first = strs[0]
for i, c in enumerate(first):
for word in strs[1:]:
if i == len(word) or word[i] != c:
return first[:i]
return firstclass Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
const string& first = strs[0];
for (int i = 0; i < (int)first.size(); i++) {
char c = first[i];
for (int j = 1; j < (int)strs.size(); j++) {
if (i == (int)strs[j].size() || strs[j][i] != c) {
return first.substr(0, i);
}
}
}
return first;
}
};function longestCommonPrefix(strs) {
const first = strs[0];
for (let i = 0; i < first.length; i++) {
const c = first[i];
for (let j = 1; j < strs.length; j++) {
if (i === strs[j].length || strs[j][i] !== c) {
return first.slice(0, i);
}
}
}
return first;
}Edge cases to test
- A single word: the whole word is the answer
- An empty string in the list: the answer is empty
- One word is a prefix of all the others
- The first letters already differ
Hints
Hint 1
The common prefix can never be longer than the shortest word.
Hint 2
Compare the words column by column: look at character i in every word before moving to i + 1.
Hint 3
Stop at the first column where a word runs out or a character differs.
FAQ
What is the best time complexity for Longest Common Prefix?
Optimal (vertical scanning) runs in O(n · m) time and O(1) extra space. n words times m, the length of the answer plus one; it never reads past the first mismatch.
Which pattern does Longest Common Prefix use?
It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Minimum Changes To Make Alternating Binary String, Rotate String.
Is there a brute force solution for Longest Common Prefix?
Yes. Brute force (shrink a candidate prefix) takes O(n · m + m²) time and O(m) space. Take the first word as the candidate.
Which edge cases should I test for Longest Common Prefix?
A single word: the whole word is the answer; An empty string in the list: the answer is empty; One word is a prefix of all the others; The first letters already differ.