14 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
In my opinion this problem statement isn't very clear. What are we prioritizing? The longest, or the most common? Because obviously the most common is going to be the shortest prefix, and the longest is going to be the least common.
This clarified it for me:
It seems that it is not to check between pair of strings but on all the strings in the array.
For example:
{"a","a","b"} should give "" as there is nothing common in all the 3 strings.
{"a", "a"} should give "a" as a is longest common prefix in all the strings.
{"abca", "abc"} as abc
{"ac", "ac", "a", "a"} as a.
Brute force approach: map every possible substring prefix from the word, and generate all the frequencies.
The most frequent word that is also just as or greater in length is the max common prefix.
Order is not preserved! (elements that are just as frequent will overwrite the previous). Using unordered_map.
Improved Python Solution
The Idea: Sort the array of strings and compare the first and last strings. This works because 1) all words have the share the common prefix, and 2) sorting ensures that the two most distant words by prefix, (which the definition of the sort) are compared. In other words, there is no need to compare the n-1th
word to the first, because we'd have to confirm with the last word anyway. Additionally, the n-1th
word is going to share a larger or same common prefix with the last word, relative to the first word. And since all words have to be in common, the last word will determine what is most common and longest.
Complexity: O(nlogn + n) time and O(1) space
Last updated