Problem
Section titled “Problem”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:
-
strs.length -
strs[i].length strs[i]consists of only lowercase English letters if it is non-empty.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Write the strings one under another, aligned on the left:
f l o w e rf l o wf l i g h t ^ column 2 differsThe 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.
Algorithm
Section titled “Algorithm”- Let
first = strs[0]. - For
kfrom0tofirst.size() - 1, and for every stringsinstrs:- if
k == s.size()(the string has ended) ors[k] != first[k], returnfirst.substr(0, k).
- if
- Every column matched: return
first.
Complexity
Section titled “Complexity”- Time: , where
Sis the total number of characters — more precisely fornstrings and an answer of lengthp, since each column inspects every string once. - Space: extra besides the returned string.
Edge cases
Section titled “Edge cases”- A single string: every column matches itself and
firstis returned. - An empty string anywhere: at
k = 0eitherfirstis empty (the loop does not run and""is returned) or that string failsk == 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 firstGive it a try first
Attempt the problem on LeetCode — the code will still be here.