Header Ads Widget

Longest Common Prefix | Leetcode solution

 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.

Code(Python):-

class Solution(object):
def longestCommonPrefix(self, strs):
pre=strs[0]
for i in range(1,len(strs)):
j=0
k=0
result=""
while(j<len(strs[i]) and k<len(pre)):
if pre[k]!=strs[i][j]:
break
else:
result+=pre[k]
j+=1
k+=1
pre=result
return pre

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

 

Post a Comment

0 Comments