Created
May 8, 2022 14:55
-
-
Save theabbie/29b307d0a96cddd20ad444d2d675a1b5 to your computer and use it in GitHub Desktop.
Longest Common Prefix using Binary Search
This file contains hidden or 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 isLCP(self, strs, k): | |
return len(set([s[:k] for s in strs])) == 1 | |
def longest_common_prefix(self, strs): | |
n = len(strs) | |
if n == 0: | |
return "" | |
beg = 0 | |
end = min([len(s) for s in strs]) | |
while beg <= end: | |
mid = (beg + end) // 2 | |
currval = self.isLCP(strs, mid) | |
nextval = self.isLCP(strs, mid + 1) | |
if (currval and not nextval) or mid >= end: | |
return strs[0][:mid] | |
elif beg == end: | |
break | |
elif currval and nextval: | |
beg = mid + 1 | |
else: | |
end = mid | |
return "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment