Find Peak Element - Problem

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

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.

Input & Output

Example 1 — Basic Peak
$ Input: nums = [1,2,3,1]
Output: 2
💡 Note: Element 3 at index 2 is a peak because 3 > 2 and 3 > 1. This satisfies the peak condition.
Example 2 — Multiple Peaks
$ Input: nums = [1,2,1,3,5,6,4]
Output: 5
💡 Note: Element 6 at index 5 is a peak because 6 > 5 and 6 > 4. Index 1 (element 2) is also a peak, but we can return any peak.
Example 3 — Single Element
$ Input: nums = [1]
Output: 0
💡 Note: With only one element, it's automatically a peak since it has no neighbors to compare with.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -231 ≤ nums[i] ≤ 231 - 1
  • nums[i] != nums[i + 1] for all valid i

Visualization

Tap to expand
Find Peak Element - Binary Search Approach INPUT nums = [1, 2, 3, 1] 1 i=0 2 i=1 3 i=2 1 i=3 PEAK Visual Representation: 1 2 3 1 nums[-1] = nums[n] = -inf Array length: n = 4 ALGORITHM STEPS 1 Initialize Pointers left=0, right=3 2 Calculate Mid mid = (0+3)/2 = 1 3 Compare Neighbors nums[1]=2 < nums[2]=3 Move right: left=2 4 Found Peak left==right, return 2 Binary Search Logic: if nums[mid] < nums[mid+1]: left = mid + 1 else: right = mid return left FINAL RESULT Peak found at index 2 1 2 3 1 Output: 2 Verification: nums[2] = 3 3 > nums[1]=2 --> OK 3 > nums[3]=1 --> OK Time: O(log n) Space: O(1) Key Insight: Binary search works because if nums[mid] < nums[mid+1], a peak MUST exist on the right side. The array either keeps increasing to the end (last element is peak) or drops somewhere (that's the peak). This guarantees finding a peak in O(log n) time by always moving toward the "uphill" direction. TutorialsPoint - Find Peak Element | Binary Search Optimal Solution
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
62.0K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen