Skip to content
thesarfo

Reference

Peak Index in a Mountain Array

Finding the peak of a strictly-increases-then-decreases array by comparing each midpoint to its right neighbor.

views 0

Given a mountain array (strictly increases to a peak, then strictly decreases), find the peak index. [0,2,4,6,5,3,1] → index 3. (LeetCode 852)

Approach: compare nums[mid] with nums[mid+1]. If nums[mid] < nums[mid+1], we’re on the uphill slope so the peak is to the right (low = mid + 1); otherwise we’re on the downhill slope so the peak is at mid or to the left (high = mid). When low == high, that’s the peak.

class Solution {
public int peakIndexInMountainArray(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) {
left = mid + 1; // uphill, move right
} else {
right = mid; // downhill, move left
}
}
return left;
}
}

Time: O(log n). Space: O(1).