Longest Common Prefix
Problem
strs, return the longest string that every
element starts with. If the strings do not even share their first character, return the
empty string "".["stamp","stack","stair"]Output"sta"["cat","dog"]Output""["abc","ab","abcd"]Output"ab"1 ≤ strs.length ≤ 200 · 0 ≤ strs[i].length ≤ 200 · lowercase English letters only
Try it yourself
class Solution {
public String longestCommonPrefix(String[] strs) {
}
}
c, and the first mismatch or the end of the shortest
string fixes the answer — no character beyond it is ever needed.Instinct Reading, comparing or rebuilding text character by character? Walk indices on a char[] and build output with a StringBuilder, never with + in a loop.
Memory hack Chars in an array, pointers on the ends, builder at the back - strings are just arrays wearing a costume.
Open the String Manipulation guide →Approaches
Brute ForceTry Every Prefix of the First String
O(n · m2)Space O(m)The answer must be a prefix of strs[0] (length m). Try
lengths from m down to 0 and return the first candidate that
every string startsWith; the empty prefix always qualifies.
public String longestCommonPrefix(String[] strs) { String first = strs[0]; for (int len = first.length(); len > 0; len--) { String cand = first.substring(0, len); boolean ok = true; for (String s : strs) { if (!s.startsWith(cand)) { ok = false; break; } } if (ok) return cand; // longest length that works } return ""; }
Obviously correct, but re-checks the same leading characters for every length.
BetterHorizontal Scan (Shrink a Running Length)
O(S)Space O(1) extraKeep len = length of the common prefix seen so far, starting with all
of strs[0]. Each next string can only shorten it: count how many
leading characters it shares with strs[0], capped at len.
S is the total number of characters.
public String longestCommonPrefix(String[] strs) { String first = strs[0]; int len = first.length(); for (int i = 1; i < strs.length && len > 0; i++) { String s = strs[i]; int j = 0; while (j < len && j < s.length() && s.charAt(j) == first.charAt(j)) j++; len = j; // the prefix can only shrink } return first.substring(0, len); }
Linear in the input, but walks each string's overlap even after a later string kills it.
OptimalVertical Scan (Column by Column)
O(n · (L+1)) ≤ O(S)Space O(1) extraCheck index c = 0, 1, 2, … across all strings at once. Stop
the moment some string is too short or differs from strs[0] at
c; the answer is strs[0][0..c). Only the L+1
columns up to the answer length L are ever read.
public String longestCommonPrefix(String[] strs) { String first = strs[0]; for (int c = 0; c < first.length(); c++) { char ch = first.charAt(c); for (int i = 1; i < strs.length; i++) { // string too short or a different character: prefix ends here if (c == strs[i].length() || strs[i].charAt(c) != ch) { return first.substring(0, c); } } } return first; // strs[0] itself is a prefix of every string }
Dry run["stamp","stack","stair"]
- c=0sctampall 's' → go on
- c=1stcampall 't' → go on
- c=2stacmpall 'a' → go on
- c=3stamcp'c' ≠ 'm' → "sta" ✔
Touches the fewest characters possible and exits on the first bad column.
At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Try Every Prefix of the First String | O(n · m2) | O(m) |
| Better | Horizontal Scan (Shrink a Running Length) | O(S) | O(1) extra |
| Optimal | Vertical Scan (Column by Column) | O(n · (L+1)) ≤ O(S) | O(1) extra |
- Reading
strs[i].charAt(c)before checking its length — index out of bounds. - Returning
nullinstead of""when nothing is shared. - Forgetting a single-string array — the whole string is the answer.
- Say out loud that the answer can never be longer than the shortest string.
- Compare horizontal vs vertical scanning and why vertical stops sooner.
- Mention the trie approach for many repeated prefix queries.