Constraints
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]consists of lowercase English letters
Clarifying Notes
- A prefix starts at index
0of a string. - The result must be shared by every string in
strs. - If any string is empty, the answer is
"".
Examples (LeetCode)
["flower","flow","flight"]->"fl"["dog","racecar","car"]->""
Approach
Use horizontal scanning:
- Initialize
prefixas the first string. - Iterate through each remaining word.
- While the current word does not start with
prefix, shrinkprefixby one character from the end. - If
prefixbecomes empty, return""immediately. - After processing all words, return
prefix.
Why this works:
- The answer must be a prefix of every word.
- Shrinking only when mismatch happens preserves the longest possible valid prefix.
- Early return avoids unnecessary work once no prefix is possible.
Complexity:
- Time:
O(S)whereSis the total number of characters examined across all comparisons - Space:
O(1)extra space - Note:
Sis not the number of strings; withnstrings of average lengthm, this is commonly expressed asO(n * m).
Implementation
export function longestCommonPrefix(strs: string[]): string {
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
const word = strs[i];
while (!word.startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (prefix === "") return "";
}
}
return prefix;
}Edge Cases Checklist
- Single-element array (answer is that string)
- Includes empty string
- No shared first character
- Entire shortest string is the prefix
- All strings identical
- Large list with small shared prefix
Test Coverage
The test suite validates:
- LeetCode baseline examples
- Single-element array behavior
- Empty-string and no-common-prefix outcomes
- Full-string and shortest-string prefix outcomes
- Repeated-character and long-prefix mismatch scenarios
- Deterministic larger input size and near-max length strings
- Defensive behavior (input array is not mutated)