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 "".

Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: longest common prefix among all strings is "fl".
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Contents

In this approach, we are going to start of with one of the string from strings array as base prefix, then compare each character from this base prefix to all other remaining strings from strings array in a vertical fashion, meaning that compare 1st charcater in all strings, then 2nd character and so on... as long as we did not go out of bounds on any string.

public class LongestCommonPrefix { static String checkCharsVertically(String[] strs) { int longest = 0; String prefix = strs[0]; for(int i=0; i<prefix.length(); i++) { for(int j=1; j<strs.length; j++) { if(i == strs[j].length() || prefix.charAt(i) != strs[j].charAt(i)) { return prefix.substring(0, longest); } } longest++; } return prefix.substring(0, longest); } }
Complexity Analysis:

Time complexity: Above code runs in O(n * m) time where n is the input strings strs length and m is the minimum length string out of all strings.
Space complexity: O(m) for the prefix we are returning.

Above implementations source code can be found at GitHub link for Java code