Skip to content

Commit e9f7dd9

Browse files
committed
Add binary search to find peak index in a mountain array
1 parent a71618f commit e9f7dd9

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
peak_mountain_array.py
3+
Author: Taha Zulfiquar
4+
Description: Finds the peak index in a mountain array using binary search.
5+
"""
6+
7+
from typing import List
8+
9+
def peak_mountain(arr: List[int]) -> int:
10+
start, end = 0, len(arr) - 1
11+
12+
while start < end:
13+
mid = start + (end - start) // 2
14+
if arr[mid] > arr[mid + 1]:
15+
end = mid
16+
else:
17+
start = mid + 1
18+
return start
19+
20+
if __name__ == "__main__":
21+
arr = [1, 2, 3, 5, 7, 8, 6, 3, 2]
22+
peak_index = peak_mountain(arr)
23+
print(f"The peak index is: {peak_index}")

0 commit comments

Comments
 (0)