EasyPythonJavaScriptTypeScript
Strings — Longest Common Prefix
AlgorithmsStrings
solve(strs) — return the longest string that is a prefix of every string instrs (non-empty array), or "" if there is none.
Take the first string as the candidate prefix and shrink it until each other string starts
with it. Or compare column by column: the prefix ends at the first index where any string is
shorter or disagrees with the first one. Either way is O(total characters).
Examples
solve(["flower","flow","flight"]) → "fl"
solve(["dog","racecar","car"]) → ""
solve(["a"]) → "a"Sample tests
Test #1Shared "fl"
Input: [["flower","flow","flight"]]
Output: "fl"
Test #2No common prefix
Input: [["dog","racecar","car"]]
Output: ""
Test #3Single string
Input: [["a"]]
Output: "a"