Longest Common Prefix - 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 "".
Note: All given inputs are in lowercase letters a-z.
Input & Output
Example 1 — Basic Case
$
Input:
strs = ["flower","flow","flight"]
›
Output:
"fl"
💡 Note:
The common prefix is "fl". All three strings start with "fl", but at position 2, "flower" and "flow" have 'o' while "flight" has 'i', so the common prefix stops there.
Example 2 — No Common Prefix
$
Input:
strs = ["dog","racecar","car"]
›
Output:
""
💡 Note:
There is no common prefix among the input strings. The first characters are 'd', 'r', and 'c' respectively, which are all different.
Example 3 — Complete Match
$
Input:
strs = ["test","test","test"]
›
Output:
"test"
💡 Note:
All strings are identical, so the entire string "test" is the common prefix.
Constraints
- 1 ≤ strs.length ≤ 200
- 0 ≤ strs[i].length ≤ 200
- strs[i] consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of strings to find common prefix
2
Character Comparison
Compare characters at same positions across all strings
3
Common Prefix
Return the longest matching prefix found
Key Takeaway
🎯 Key Insight: Compare strings character by character vertically - stop at first mismatch to get optimal performance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code