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
Longest Common Prefix ProblemInput: String Array"flower""flow""flight"Process: Compare Charactersfl?MatchMatchDifferOutput: "fl""fl"Find the longest string that is a prefix of all input stringsStop at first character position where strings differ
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
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
52.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen