LeetCode — Longest Common Prefix

MaheswaraReddy
Dec 17, 2022

--

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

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

SourceCode

class Solution:

def longestCommonPrefix(self, strs: List[str]) -> str:

str_sorted = sorted(strs, key=len)

init_str = list(str_sorted[0])

for i in range(1, len(str_sorted)):

temp_lst = list(str_sorted[i])

k = 0

prefix = []

for j in init_str:

if j == temp_lst[k]:

prefix.append(j)

else:

break

k = k + 1

init_str = ‘’.join([str(elem) for elem in prefix])

if len(init_str) > 0:

return ‘’.join([str(elem) for elem in init_str])

else:

return “”

--

--

No responses yet