I have a list as below:
strs = ["flowers", "flow", "flight"]
Now, I want to find the longest prefix
of the elements from the list. If there is no match then it should return ""
. I am trying to use the 'Divide and Conquer'
rule for solving the problem. Below is my code:
strs = ["flowers", "flow", "flight"]
firstHalf = ""
secondHalf = ""
def longestCommonPrefix(strs) -> str:
minValue = min(len(i) for i in strs)
length = len(strs)
middle_index = length // 2
firstHalf = strs[:middle_index]
secondHalf = strs[middle_index:]
minSecondHalfValue = min(len(i) for i in secondHalf)
matchingString=[] #Creating a stack to append the matching characters
for i in range(minSecondHalfValue):
secondHalf[0][i] == secondHalf[1][i]
return secondHalf
print(longestCommonPrefix(strs))
I was able to find the mid
and divide
the list into two parts. Now I am trying to use the second half and get the longest prefix but am unable to do so. I have had created a stack
where I would be adding the continuous matching characters and then I would use it to compare with the firstHalf
but how can I compare the get the continuous matching characters from start
?
Expected output:
"fl"
Just a suggestion would also help. I can give it a try.