forked from partho-maple/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Shifted_Binary_Search.py
61 lines (46 loc) · 1.77 KB
/
Shifted_Binary_Search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Solution #1 - Recursive Solution
# O(logn) time | O(logn) space
def shiftedBinarySearch(array, target):
return shiftedBinarySearchHelper(array, target, 0, len(array) - 1)
def shiftedBinarySearchHelper(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potentialMatch = array[middle]
leftNum = array[left]
rightNum = array[right]
if potentialMatch == target:
return middle
elif leftNum <= potentialMatch:
if target < potentialMatch and target >= leftNum:
return shiftedBinarySearchHelper(array, target, left, middle - 1)
else:
return shiftedBinarySearchHelper(array, target, middle + 1, right)
else:
if target > potentialMatch and target <= rightNum:
return shiftedBinarySearchHelper(array, target, middle + 1, right)
else:
return shiftedBinarySearchHelper(array, target, left, middle - 1)
# Solution #2 - Iterative Solution
# O(logn) time | O(1) space
def shiftedBinarySearch(array, target):
return shiftedBinarySearchHelper(array, target, 0, len(array) - 1)
def shiftedBinarySearchHelper(array, target, left, right):
while left <= right:
middle = (left + right) // 2
potentialMatch = array[middle]
leftNum = array[left]
rightNum = array[right]
if potentialMatch == target:
return potentialMatch
elif leftNum <= potentialMatch:
if target < potentialMatch and target >= leftNum:
right = middle - 1
else:
left = middle + 1
else:
if target > potentialMatch and target <= leftNum:
left = middle + 1
else:
right = middle - 1
return -1