Skip to content
MediumBinary SearchAI interview only

Find Peak Element

Asked atgoogleamazonmetamicrosoftappleuber

01 · 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.

02 · Examples

Example 01
Input
nums = [1,2,3,1]
Output
2

3 is a peak element at index 2.

Example 02
Input
nums = [1,2,1,3,5,6,4]
Output
5

6 is a peak element at index 5. Index 1 (value 2) is also a valid answer.

Example 03
Input
nums = [1]
Output
0

Since nums[-1] and nums[1] are both -∞, nums[0] = 1 is a peak.

03 · Constraints

  • 011 <= nums.length <= 1000
  • 02-231 <= nums[i] <= 231 - 1
  • 03nums[i] != nums[i + 1] for all valid i.

04 · Optimal complexity

Time
O(log n)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.