SDE & MLE Prep

162. Find Peak Element

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