Longest Common Prefix - Problem
Find the longest common prefix among an array of strings. You need to determine the longest string that appears at the beginning of every string in the given array.

The Goal: Given an array of strings, find the longest prefix that is common to all strings. If no common prefix exists, return an empty string.

Input: An array of strings strs
Output: A string representing the longest common prefix

Example: For ["flower", "flow", "flight"], the answer is "fl" because all three strings start with "fl".

Input & Output

example_1.py โ€” Python
$ Input: ["flower","flow","flight"]
โ€บ Output: "fl"
๐Ÿ’ก Note: The longest common prefix among all strings is "fl". All three strings start with these two characters.
example_2.py โ€” Python
$ Input: ["dog","racecar","car"]
โ€บ Output: ""
๐Ÿ’ก Note: There is no common prefix among the input strings. The first characters are already different: 'd', 'r', 'c'.
example_3.py โ€” Python
$ Input: ["interspecies","interstellar","interstate"]
โ€บ Output: "inters"
๐Ÿ’ก Note: All three strings share the common prefix "inters" before they start to differ.

Visualization

Tap to expand
Finding Longest Common PrefixInput: ["flower", "flow", "flight"]f l o w e rf l o wf l i g h tfโœ“ Matchlโœ“ Matchooiโœ— MismatchResult: "fl"
Understanding the Visualization
1
Line up all strings
Arrange strings vertically to compare position by position
2
Check position 0
All strings have 'f' - this character is part of common prefix
3
Check position 1
All strings have 'l' - extend common prefix to 'fl'
4
Check position 2
Mismatch found: 'o', 'o', 'i' - stop and return 'fl'
Key Takeaway
๐ŸŽฏ Key Insight: Compare characters position by position across all strings simultaneously. Stop at the first mismatch to get the longest common prefix efficiently.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(S)

Where S is the sum of all characters in all strings. In worst case, we examine every character once.

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track current position and build result.

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค strs.length โ‰ค 200
  • 0 โ‰ค strs[i].length โ‰ค 200
  • strs[i] consists of only lowercase English letters
Asked in
Google 85 Amazon 72 Microsoft 68 Meta 45
68.5K Views
High Frequency
~15 min Avg. Time
2.8K 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