Given an array of integers arr
that is a mountain array, return the peak index in the mountain array.
A mountain array is defined as an array that:
arr.length >= 3
i
with 0 < i < arr.length - 1
such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
You must solve it in O(log(n))
time complexity.
To solve this problem efficiently in O(log(n))
time complexity, we can use a binary search approach. Here’s how:
left
at the start of the array and right
at the end of the array.left
is less than right
:
mid
.arr[mid]
is less than arr[mid + 1]
, it means the peak is in the right half, so move left
to mid + 1
.arr[mid]
is greater than or equal to arr[mid + 1]
, it means the peak is in the left half, so move right
to mid
.left
will be pointing at the peak index.def peakIndexInMountainArray(arr: int) -> int:
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1
else:
right = mid
return left
O(log(n))
because each step of the binary search cuts the search space in half.O(1)
because no additional space is used that scales with the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?