Created
February 7, 2022 02:06
-
-
Save amarjitdhillon/8eb680cdde08d775b4c910ab2750855a to your computer and use it in GitHub Desktop.
Longest Common Prefix Leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def longestCommonPrefix(self, strs: List[str]) -> str: | |
res = '' # final output | |
if len(strs) == 0: # special case | |
return res | |
min_element = min(strs, key = len) # find the min length word in strs | |
for i in range(len(min_element)): | |
for s in strs: | |
if s[i] != strs[0][i]: # return if chars dont match with the first word | |
return res | |
res += s[i] # if all the chars match, then add it to the result | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment