← Back to Leo Academy Masterclass

Problem #162: Find Peak Element

Medium Binary Search

Intuition & Strategy Breakdown

Use binary search. If nums[mid] < nums[mid + 1], a peak must exist in the right half; otherwise a peak exists in the left half.

Python Solution

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1
        
        while left < right:
            mid = (left + right) // 2
            # Compare mid with next element
            if nums[mid] < nums[mid + 1]:
                # We are on an upward slope. 
                # Peak must be on the right.
                left = mid + 1
            else:
                # We are on a downward slope.
                # Peak could be mid or on the left.
                right = mid
        
        return left

Java Solution

class Solution {
    public int findPeakElement(int[] nums) {
        int left = 0, right = nums.length - 1;
        
        while (left < right) {
            int mid = (left + right) / 2;
            // Compare mid with next element
            if (nums[mid] < nums[mid + 1]) {
                // We are on an upward slope.
                // Peak must be on the right.
                left = mid + 1;
            } else {
                // We are on a downward slope.
                // Peak could be mid or on the left.
                right = mid;
            }
        }
        
        return left;
    }
}
Watch Interactive Video on Leo Academy Main App