1185. Find in Mountain Array
My accepted Python solution to LeetCode problem 1185, Find in Mountain Array, running in 28ms.
- Difficulty: Hard
- Python
- Runtime 28ms
- Memory 18.5MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 28ms, memory 18.5MB, accepted 2026-01-02.
# """
# This is MountainArray's API interface.
# You should not implement it, or speculate about its implementation
# """
#class MountainArray:
# def get(self, index: int) -> int:
# def length(self) -> int:
class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
n = mountain_arr.length()
# Find peak
left, right = 0, n - 1
while left < right:
mid = (left + right) // 2
if mountain_arr.get(mid) < mountain_arr.get(mid + 1):
left = mid + 1
else:
right = mid
peak = left
# Binary search in ascending part
left, right = 0, peak
while left <= right:
mid = (left + right) // 2
val = mountain_arr.get(mid)
if val == target:
return mid
elif val < target:
left = mid + 1
else:
right = mid - 1
# Binary search in descending part
left, right = peak, n - 1
while left <= right:
mid = (left + right) // 2
val = mountain_arr.get(mid)
if val == target:
return mid
elif val > target:
left = mid + 1
else:
right = mid - 1
return -1