[LeetCode] Top Interview 150 Problems Solving # 14 Longest Common Prefix
Understanding the Problem
It is simply to find the common prefix in between the strings in the list strs. strs contains strings like strs = ["flower","flow","flight"]. In this case the common prefix will be ”fl” which is included in every string in common. When there is no common prefix, an empty string will be returned.
Approach
The only idea to solve the problem was to go with two for loops with O(n²). The base characters to compare other characters in each string is the first string’s characters.
Solution
There were cases when there is a string in strs but the string is empty like ””, so I returned this when the string length is 1 and it’s empty.
Then try to pile characters in s = ““ if a character in each string is common. Afterwards, it takes steps as follows.
The loop occurs in
strs[0]. and another loop goes in each string asword.Only if the index
iis less than the length of the word, check if the character is common. If not common, I returnedsto finish the code.If
iis equal or greater thanlen(word), returnsas it is no use running the code any further.Other than that, add the character to
s.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 1:
return strs[0]
s = ""
for i in range(len(strs[0])):
for word in strs:
if i < len(word): # only when index is within range
if word[i] != strs[0][i]:
return s
elif i >= len(word):
return s
s += strs[0][i]
return s
Reflection
I have looked up other solutions on LeetCode but it was plausible that everyone chose to solve the problem with O(n²) just like I did it. I believe there should be a better solution though.
About the author
South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?
Comments
Join the discussionNo comments yet. Be the first to comment.




