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
Output: A string representing the longest common prefix
Example: For
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
strsOutput: 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
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.
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track current position and build result.
โ Linear Space
Constraints
- 1 โค strs.length โค 200
- 0 โค strs[i].length โค 200
- strs[i] consists of only lowercase English letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code