Algorithm Day109 - 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 "".
💬 Examples
Example 1
1 | Input: strs = ["flower","flow","flight"] |
Example 2
1 | Input: strs = ["dog","racecar","car"] |
Explanation: There is no common prefix among the input strings.
💡 Intuition
A common and simple approach is to start from the first string as the prefix, and then gradually shorten it while checking against other strings.
Stop when the prefix no longer matches.
🔢 Java Code (Vertical Scanning)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(S) — S = total number of characters in all strings (each char checked at most once).
- Space: O(1) — no extra data structure used.
✍️ Summary
- Start with the first string as prefix and reduce it when mismatches occur.
- Efficient for small/medium input sizes.
- A clean and intuitive string problem that often appears early in interviews.