Suppose we have a set of strings in an array. We have to find the Longest Common Prefix amongst the string in the array. Here we will assume that all strings are lower case strings. And if there is no common prefix, then return “”.
So if the array of a string is like ["school", "schedule","Scotland"], then the Longest Common Prefix is “sc” as this is present in all of these string.
To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched.
Let us see the implementation to get a better understanding
Example (Python)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs[0] for i in range(1,len(strs)): temp = "" if len(current) == 0: break for j in range(len(strs[i])): if j<len(current) and current[j] == strs[i][j]: temp+=current[j] else: break current = temp return current input_list = ["school","schedule","scotland"] ob1 = Solution() print(ob1.longestCommonPrefix(input_list))
Input
["school","schedule","scotland"]
Output
"sc"