Instagram
youtube
Facebook
Twitter

Longest Common Prefix Leetcode Solution

In this tutorial, we will solve the leetcode problem longest common prefix in python.

Task:

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.

Solution:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        new_str = ""
        if len(strs) == 0:
            return ""
        elif len(strs) == 1:
            return strs[0]
        strs.sort()
        last = min(len(strs[0]), len(strs[-1]))
        j = 0
        while j < last and (strs[0][j] == strs[len(strs)-1][j]):
            new_str += strs[0][j]
            j += 1
        return new_str

Steps:

setp1: first we make an empty string, and added two base cases.

step2: Now, we sort the string and set the variable last to the minimum of string at index 0 and last index.

step3: Now, we run a while loop till last and check the string characters, and adding it the new string while updating the index variable j.

step4: After the loop we return the new string as our required solution.