Longest Common Prefix
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""
.
Example 1:
Example 2:
Note:
All given inputs are in lowercase lettersa-z
.
Analysis
For multiple string comparison, what will be the fastest way to fail. It's intuitive to think of finding the shortest string first. And in worst case, it would involve n
equal strings with length m
and the algorithm performs S = m*n
character comparisons. In best case it would be n * minLen
, where minLen is the length of shortest string in the array.
Other approaches, like divide and conquer, binary search, building trie, see:
https://leetcode.com/articles/longest-common-prefix/
Solution
Two pass, one pass to get shortest string length, second to check common prefix
Reference
Last updated