162. Find Peak Element
Asked at 29Meta86Microsoft63Bloomberg62Amazon60Google57Apple43Adobe55Infosys54tcs46Urban Company89IXL72Samsung71Siemens65Akamai64Docusign64Yahoo61Waymo58ServiceNow55Accenture54TikTok53eBay53PayPal51Uber50ByteDance50Netflix49Nvidia48Visa39Goldman Sachs36Oracle27
Problem
A peak is an element strictly greater than its neighbours, and positions outside the array count as −∞. Adjacent values in nums are never equal. Return the index of any peak, in O(log n).
Example: [1,2,3,1] → 2; [1,2,1,3,5,6,4] → 1 or 5
If nums[mid] < nums[mid+1] we're on an uphill slope → a peak exists to the right; else a peak is at mid or left. (Edges count as −∞.)
Complexity: O(log n).
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo
assert Solution().findPeakElement([1, 2, 3, 1]) == 2
assert Solution().findPeakElement([1, 2, 1, 3, 5, 6, 4]) in (1, 5)
class Solution {
public int findPeakElement(int[] nums) {
int lo = 0, hi = nums.length - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < nums[mid + 1]) lo = mid + 1; else hi = mid;
}
return lo;
}
}
func findPeakElement(nums []int) int {
lo, hi := 0, len(nums)-1
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] < nums[mid+1] { // uphill: a peak lies to the right
lo = mid + 1
} else {
hi = mid
}
}
return lo
}