Skip to content

Instantly share code, notes, and snippets.

@tanmay27vats
Created February 1, 2022 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanmay27vats/6abf35f31e2ca726503371b35ae6aad8 to your computer and use it in GitHub Desktop.
Save tanmay27vats/6abf35f31e2ca726503371b35ae6aad8 to your computer and use it in GitHub Desktop.
[Python] Longest Common Prefix - 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 …
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ""
common_prefix = strs[0]
for i in range(1,len(strs)):
temp = ""
if len(common_prefix) == 0:
break
for j in range(len(strs[i])):
if j<len(common_prefix) and common_prefix[j] == strs[i][j]:
temp+=common_prefix[j]
else:
break
common_prefix = temp
return common_prefix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment