Longest Common Prefix
Easy
Topics
You are given a list of non-empty words. Return the longest string that every word in the list starts with. If the words do not all share even their first letter, return the empty string "".
Example 1
The shaded columns agree across every word, so the answer is
sta. Scanning column by column stops at the first disagreement, which means the work is bounded by the answer’s length rather than by the longest word.One row per word, aligned so the shared prefix lines up.
Input: words = ["station","stats","stack"] Output: "sta"
Example 2
The first characters already differ, so the common prefix is empty.
Input: words = ["kiwi","lime","kale"] Output: "" Explanation: "lime" does not start with "k".
Example 3
Input: words = ["solo"] Output: "solo"
Constraints
- 1 <= words.length <= 200
- 1 <= words[i].length <= 200
- words[i] consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The shared prefix can never be longer than the shortest word, and it ends at the first column where any two words disagree. So read the words column by column, top to bottom, and stop at the first mismatch.
Approach
- Take the first word as the candidate.
- For each column index
iof the candidate, check every other word: if it is shorter thani + 1or has a different character ati, the answer is the candidate cut to lengthi. - If no column fails, the whole first word is the prefix.
Dry Run
words = ["station", "stats", "stack"]
The loop carries a LENGTH rather than a prefix string, because re-slicing the
prefix once per word is what would quietly cost the O(1) space.
length starts at len("station") = 7
vs "stats" limit = min(7, 5) = 5
s==s t==t a==a t==t then 'i' vs 's' differ length = 4
vs "stack" limit = min(4, 5) = 4
s==s t==t a==a then 't' vs 'c' differ length = 3
answer words[0][:3] = "sta"
limit is doing two jobs in one expression. min(..., len(word)) keeps the scan
inside a shorter word: replace it with a bare length and ["abcdef", "abc"] raises
IndexError: string index out of range instead of returning "abc". And min(length,
...) means each word is only ever checked against the prefix that survived the
earlier words, which is why "stats" stops at column 4 instead of re-walking all
seven characters of "station".
length only ever decreases, so the early return "" when it reaches 0 is safe --
no later word can revive a prefix that is already empty.Complexity
- Time — O(S): S is the total number of characters; each is compared at most once.
- Space — O(1): beyond the returned slice.
Common Pitfalls
- Forgetting the length check when a later word is shorter than the first.
- Sorting the words first and comparing the first and last also works, but costs O(S log n) for no benefit.
Full Solution — all languages
class Solution:
def longestCommonPrefix(self, words):
if not words:
return ""
# Track how long the common prefix is, rather than re-slicing a string.
# prefix = prefix[:i] allocates a new string on every word, and words[1:]
# copies the whole list -- together they give up the O(1) space claim.
length = len(words[0])
for w in range(1, len(words)):
word = words[w]
limit = min(length, len(word))
i = 0
while i < limit and words[0][i] == word[i]:
i += 1
length = i
if length == 0:
return ""
return words[0][:length] # one allocation, for the result onlyimport java.util.*;
class Solution {
public String longestCommonPrefix(String[] words) {
if (words == null || words.length == 0) return "";
// Track the prefix LENGTH; substring per word would allocate each time.
int length = words[0].length();
for (int w = 1; w < words.length; w++) {
int limit = Math.min(length, words[w].length());
int i = 0;
while (i < limit && words[0].charAt(i) == words[w].charAt(i)) i++;
length = i;
if (length == 0) return "";
}
return words[0].substring(0, length); // one allocation, the result
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string longestCommonPrefix(vector<string>& words) {
if (words.empty()) return "";
string prefix = words[0];
for (size_t k = 1; k < words.size(); k++) {
size_t i = 0;
while (i < prefix.size() && i < words[k].size() && prefix[i] == words[k][i]) i++;
prefix = prefix.substr(0, i);
if (prefix.empty()) return "";
}
return prefix;
}
};/**
* @param {string[]} words
* @return {string}
*/
var longestCommonPrefix = function (words) {
if (!words || words.length === 0) return "";
// Track the prefix length rather than re-slicing.
let length = words[0].length;
for (let w = 1; w < words.length; w++) {
const limit = Math.min(length, words[w].length);
let i = 0;
while (i < limit && words[0][i] === words[w][i]) i++;
length = i;
if (length === 0) return "";
}
return words[0].slice(0, length);
};