← Back to Binary Search

Find the Peak Element

2 of 5

Exercise 5: Find the Peak Element

Your Task

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

Write a function find_peak(nums) that returns the index of any peak element in nums.

  • You may assume nums[-1] and nums[n] are treated as -∞ (negative infinity).
  • There is always at least one peak.
  • Your solution must run in O(log n).

Examples

print(find_peak([1, 2, 3, 1])) # 2 (nums[2] = 3 is a peak) print(find_peak([1, 2, 1, 3, 5])) # 1 or 4 (either is valid) print(find_peak([1])) # 0 print(find_peak([3, 2, 1])) # 0 (nums[0] = 3 is a peak) print(find_peak([1, 2, 3])) # 2 (nums[2] = 3 is a peak)

Expected Complexity

Complexity
TimeO(log n) — binary search
SpaceO(1)

Starter Code

def find_peak(nums): pass print(find_peak([1, 2, 3, 1])) # 2 print(find_peak([1, 2, 1, 3, 5])) # 1 or 4 print(find_peak([1])) # 0 print(find_peak([3, 2, 1])) # 0 print(find_peak([1, 2, 3])) # 2

Hints

Try it yourself

Code: Find the Peak Element

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...