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
Output: "fl"
Explanation: longest common prefix among all strings is "fl".
Output: 4
Explanation: The last word is "moon" with length 4.
Output: 6
Explanation: The last word is "joyboy" with length 6.
Contents
Solution 1 - check character by character from all strings in a vertical fashion
In this approach, we are going to start of with one of the string from strings array as
-
We will create a function
checkCharsVertically that takes input argument stringsstrs . -
Create a variable
longest to keep track of longest prefix length found so far, and take the first element fromstrs array as base prefix. -
Then, loop through all strings vertically, 1st character in all strings and then 2nd character and so on,
when all strings have a character in common then increment
longest variable, continue this until one of string have no matching character. -
When a character match is not found in any string or at the end simply return substring from
base prefix from0 andlongest indexes.
When input array has only one string, then it comes to return statement at the end.
Complexity Analysis:
Time complexity: Above code runs in O(n * m) time where
Space complexity: O(m) for the prefix we are returning.
Above implementations source code can be found at