Skip to main content

Find Peak Element

Question

Given an array of integers, find the index of the peak element in the array. Peak element is defined as an element which is greater than its neighbors. If the array contains multiple peak elements, return the index of any one of the peak elements.

Example 1
Input: [1,2,1,3,5,6,4]
Output: 5 (peak element)

Solution

all//Find Peak Element.py


def findPeakElement(nums):
l = 0
r = len(nums) - 1

while l < r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
r = mid
else:
l = mid + 1
return l

nums = [1,2,3,4,5,6,7,8,9]

print(findPeakElement(nums)) # Output: 8