852. Peak Index in a Mountain Array
Problem
arr is a mountain: strictly increasing up to one peak, then strictly decreasing. Return the peak's index in O(log n).
Example: [0,10,5,2] → 1
Find the first index where the array starts descending: arr[mid] > arr[mid + 1].
Complexity: O(log n).
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
lo, hi = 0, len(arr) - 1
while lo < hi:
mid = (lo + hi) // 2
if arr[mid] > arr[mid + 1]:
hi = mid
else:
lo = mid + 1
return lo
assert Solution().peakIndexInMountainArray([0, 1, 0]) == 1
assert Solution().peakIndexInMountainArray([0, 10, 5, 2]) == 1
assert Solution().peakIndexInMountainArray([3, 5, 3, 2, 0]) == 1
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int lo = 0, hi = arr.length - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid] > arr[mid + 1]) hi = mid; else lo = mid + 1;
}
return lo;
}
}
func peakIndexInMountainArray(arr []int) int {
lo, hi := 0, len(arr)-1
for lo < hi { // first index where the array starts descending
mid := lo + (hi-lo)/2
if arr[mid] > arr[mid+1] {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}