Peak Index In A Mountain Array Problem
Description
LeetCode Problem 852.
Let's call an array arr a mountainif the following properties hold:
- arr.length >= 3
- There exists some i with0 < i< arr.length - 1such that:
- arr[0] < arr[1] < ... arr[i-1] < arr[i]
- arr[i] > arr[i+1] > ... > arr[arr.length - 1]
Given an integer array arr that is guaranteed to bea mountain, return anyisuch thatarr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
Example 1:
Input: arr = [0,1,0]
Output: 1
Example 2:
Input: arr = [0,2,1,0]
Output: 1
Example 3:
Input: arr = [0,10,5,2]
Output: 1
Example 4:
Input: arr = [3,4,5,1]
Output: 2
Example 5:
Input: arr = [24,69,100,99,79,78,67,36,26,19]
Output: 2
Constraints:
- 3 <= arr.length <= 10^4
- 0 <= arr[i] <= 10^6
- arr is guaranteed to be a mountain array.
Solution
Approach: Binary Search on the Slope
A linear scan for the largest element works in O(n), but the mountain shape lets us binary search.
Compare arr[mid] with its right neighbour arr[mid + 1]:
- If
arr[mid] < arr[mid + 1], we are on the rising side, so the peak is strictly to the right:low = mid + 1. - Otherwise we are on the falling side (or at the peak), so the peak is at
midor to its left:high = mid.
Stop when low == high; that index is the peak.
Two details keep this correct. First, mid is rounded down and the loop runs only while low < high, so mid + 1 is always a valid index. Second, in the falling case we set high = mid, not mid - 1, because mid itself may be the peak. The values are strictly increasing then strictly decreasing, so neighbours are never equal and each comparison tells us the side.
Complexity: O(log n) time and O(1) space, where n is the length of arr.
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
low, high = 0, len(arr) - 1
while low < high:
mid = (low + high) // 2
if arr[mid] < arr[mid + 1]:
low = mid + 1 # still climbing: the peak is to the right of mid
else:
high = mid # going down: mid may be the peak, or it is to the left
return low