Skip to content

Commit eb52b3a

Browse files
committed
added alternate binary search | added peak element
1 parent 545d5d5 commit eb52b3a

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# alternative binary search
2+
# - based on "efficient iteration"
3+
# - make jumps and slow down as we get close to target
4+
# - time complexity => O(logn)
5+
6+
# iterative
7+
def bsearch_alt(target, arr):
8+
n = len(arr)
9+
k = 0
10+
i = n // 2
11+
while (i >= 1):
12+
while (k + i < n) and (arr[k + i] <= target):
13+
k = k + 1
14+
i = i // 2
15+
16+
return k if arr[k] == target else -1
17+
18+
19+
20+
print(bsearch_alt(4, [1, 2, 3, 4, 5]))
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# find peak element | leetcode 162 | https://leetcode.com/problems/find-peak-element/
2+
# using binary search to determine
3+
# if the "middle" element is on a +ve / -ve slope
4+
5+
class Solution:
6+
def findPeakElement(self, nums: list[int]) -> int:
7+
a = 0
8+
b = len(nums) - 1
9+
while a < b:
10+
k = (a + b) // 2
11+
if nums[k] > nums[k + 1]:
12+
b = k
13+
else:
14+
a = k + 1
15+
16+
return a

0 commit comments

Comments
 (0)