Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Solution: Order-agnostic Binary Search
.....
.....
.....
Like the course? Get enrolled and start learning!
A
Anonymous
· 2 years ago
class Solution: def search(self,arr, key): def binary_search(goleft): left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == key: return mid elif goleft(key, arr[mid]): right = mid - 1 else: left = mid + 1 return -1 is_ascending = arr[0] < arr[-1] if is_ascending: return binary_search(lambda key,mid: key < mid ) else: return binary_search(lambda key,mid: key > mid )
A
Anonymous
· 3 years ago
class Solution: def search(self,arr, key): if len(arr) == 0: return -1 if arr[0] == arr[-1]: return 0 if arr[0] == key else -1 inc = arr[-1] > arr[0] i = 0 j = len(arr)-1 while i < j: mid = (i+j)//2 if arr[mid] == key: return mid if arr[mid] > key and inc: j = mid - 1 else: i = mid +1 if arr[i] == key: return i return -1 # element not found
I have this solution, which should work. For example. for the array [1,1,1,1,1] it returns 0, but the solution says that it should return 2. I believe this is a mistake because the problem description does not specify how exactly duplicates should be handled.
A
Anonymous
· 4 years ago
A little shorter, perhaps more confusing:
if ascending == (arr[mid] < key): start = mid+1 else: end = mid-1
Reading Progress
0%