Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created May 8, 2022 14:55
Show Gist options
  • Save theabbie/29b307d0a96cddd20ad444d2d675a1b5 to your computer and use it in GitHub Desktop.
Save theabbie/29b307d0a96cddd20ad444d2d675a1b5 to your computer and use it in GitHub Desktop.
Longest Common Prefix using Binary Search
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