Find the longest common prefix among an array of strings
Filed under Oracle · Also reported at VMware
Free read 1 of 3Confirm expected inputs, empty array behavior, and string constraints.
The question
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 "".
Constraints
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters if non-empty.
Examples
- Input
- strs = ["flower","flow","flight"]
- Output
- "fl"
- Why
- "fl" is the longest common prefix for all three strings.
- Input
- strs = ["dog","racecar","car"]
- Output
- ""
- Why
- There is no common prefix among the input strings.
Approach
Confirm expected inputs, empty array behavior, and string constraints.
Compare characters of the first string with all other strings column by column.
Use horizontal scanning or sorting: compare the first and last strings lexicographically after sorting the array.
Handle single-element arrays and cases where one string is a prefix of another.
Tips
- What they are testing: Test with an empty array, a single string, strings with no common prefix, and identical strings.
- Common mistake: Failing to handle empty strings within the array or out-of-bounds index errors during vertical scanning.
Follow-ups
- Optimize the solution for better space or time complexity.
Related Oracle questions
Collected from public candidate posts and coding forums. Updated Nov 2026.