Find Peak Element


find-peak-element


Problem Statement

A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find any peak element and return its index.

You may assume:

The algorithm must run in O(log n) time complexity.


Examples


Constraints


Intuition

We are required to find a peak in logarithmic time, which strongly suggests using binary search.

We can think of the array as a mountain range:

This idea is valid because eventually, we will reach a point where an element is greater than both neighbors.


Approach

  1. Initialize start = 0, end = nums.length - 1

  2. Use binary search:

    • While start < end:

      • Calculate mid = start + (end - start) / 2

      • If nums[mid] > nums[mid + 1], then search in the left half including mid: end = mid

      • Else, search in the right half: start = mid + 1

  3. When the loop ends, start == end, which points to a peak.

  4. Return start


Code in Java

class Solution {
    public int findPeakElement(int[] nums) {
        int start = 0;
        int end = nums.length - 1;

        while (start < end) {
            int mid = start + (end - start) / 2;

            if (nums[mid] > nums[mid + 1]) {
                end = mid; // peak is on the left or at mid
            } else {
                start = mid + 1; // peak is on the right
            }
        }

        return start; // or return end (both are equal here)
    }
}

Time and Space Complexity


Dry Run

Input:

nums = [1, 2, 1, 3, 5, 6, 4]

Steps:

  1. start = 0, end = 6mid = 3, nums[3] = 3, nums[4] = 5
    → 3 < 5 → move right → start = 4

  2. start = 4, end = 6mid = 5, nums[5] = 6, nums[6] = 4
    → 6 > 4 → move left → end = 5

  3. start = 4, end = 5mid = 4, nums[4] = 5, nums[5] = 6
    → 5 < 6 → move right → start = 5

Now start == end == 5

Return 5


Conclusion

This problem is a great example of binary search used creatively to satisfy custom conditions. By analyzing the slope of the array (increasing or decreasing at the midpoint), we efficiently narrow down the search space to locate a peak. The logic guarantees that we will always find at least one peak using this method in O(log n) time.