Skip to content

Longest Common Prefix

Solve on LeetCodeEasy
Time
Space

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1≤1 \le strs.length ≤200\le 200
  • 0≤0 \le strs[i].length ≤200\le 200
  • strs[i] consists of only lowercase English letters if it is non-empty.

Write the strings one under another, aligned on the left:

f l o w e r
f l o w
f l i g h t
^ column 2 differs

The common prefix is made of the columns, read from the left, in which every string has the same character. So scan vertically: for column k = 0, 1, 2, ..., check s[k] of every string against first[k] (the first string’s character). The first column where some string is too short or has a different character ends the prefix — it is first[0..k). If no column fails, the whole first string is the prefix.

Scanning column by column stops at the first mismatch, so we never read characters beyond the answer’s length plus one column, even if some strings are very long.

  1. Let first = strs[0].
  2. For k from 0 to first.size() - 1, and for every string s in strs:
    • if k == s.size() (the string has ended) or s[k] != first[k], return first.substr(0, k).
  3. Every column matched: return first.
  • Time: O(S)O(S), where S is the total number of characters — more precisely O(n⋅(p+1))O(n \cdot (p + 1)) for n strings and an answer of length p, since each column inspects every string once.
  • Space: O(1)O(1) extra besides the returned string.
  • A single string: every column matches itself and first is returned.
  • An empty string anywhere: at k = 0 either first is empty (the loop does not run and "" is returned) or that string fails k == s.size() and "" is returned.
  • A string that is a prefix of the others (like "flow" vs "flower"): the length check stops the scan before reading past its end.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
const string& first = strs[0];
for (int k = 0; k < (int)first.size(); k++) {
for (const string& s : strs) {
if (k == (int)s.size() || s[k] != first[k]) return first.substr(0, k);
}
}
return first;
}
};
class Solution {
public String longestCommonPrefix(String[] strs) {
String first = strs[0];
for (int k = 0; k < first.length(); k++) {
for (String s : strs) {
if (k == s.length() || s.charAt(k) != first.charAt(k)) return first.substring(0, k);
}
}
return first;
}
}
class Solution:
def longestCommonPrefix(self, strs: list[str]) -> str:
first = strs[0]
for k, c in enumerate(first):
for s in strs:
if k == len(s) or s[k] != c:
return first[:k]
return first

Give it a try first

Attempt the problem on LeetCode — the code will still be here.