2 of 5
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.
nums[-1] and nums[n] are treated as -∞ (negative infinity).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)
| Complexity | |
|---|---|
| Time | O(log n) — binary search |
| Space | O(1) |
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