JavaScriptMediumStrings20 min
Find the longest common prefix
Return the longest prefix shared by all input strings; return an empty string for an empty list. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess compare each prefix position across all strings.
Input
A JSON array of ASCII strings.
Output
Print one compact JSON value: a string.
Constraints
0 <= number of strings <= 1000; each string length <= 1000.
Example
Input
["flower","flow","flight"]
Output
"fl"
Example 2 input
["test","test"]
Output
"test"
Boundary case: An empty list has an empty common prefix
Public test cases (2)
Input
["flower","flow","flight"]
Expected output
"fl"
Input
["dog","racecar","car"]
Expected output
""
Hints (2)
- Stop at the first disagreement or exhausted string
- An empty list has an empty common prefix
Target complexity: time O(total input characters + number of strings) · space O(p), where p is the returned prefix length
