How to Find Peak Element in the Array in Python?

Hello Friends Today, through this tutorial, I will tell you How to Find Peak Element in the Array in Python?

Here’s how to find the peak element in an array using Python:

Using a loop

This method iterates through the array and compares each element with its neighbors. If an element is greater than both its neighbors, it’s a peak element.

def find_peak_element(nums):

"""
Finds the index of a peak element in the array.
Args:
nums: A list of integers.
Returns:
The index of the peak element, or -1 if not found.
"""
n = len(nums)
if n == 1:
return 0
# Check first and last elements as they cannot be compared with both neighbors
if nums[0] > nums[1]:
return 0
if nums[n - 1] > nums[n - 2]:
return n - 1
# Iterate through the rest of the array
for i in range(1, n - 1):
if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:
return i
return -1
# Example usage
nums = [1, 2, 3, 1, 5]
peak_index = find_peak_element(nums)
if peak_index != -1:
print(f"Peak element found at index {peak_index} with value {nums[peak_index]}")
else:
print("No peak element found")

Explanation:

1. The function iterates through the array, skipping the first and last elements as they cannot be compared with both neighbors.
2. It checks if the current element is greater than both its neighbors and returns its index if true.
3. If no peak element is found, it returns -1.