Array Peak Element Finder
Given a non-empty array of integers where each element represents the height of a bar on a graph, find a peak element and return its index. A peak element is an element that is greater than its neighbors. For elements at the boundaries of the array, consider only one neighbor. The function should return the index of the first peak if multiple peaks exist.
[ 1, 3, 20, 4, 1, 0 ]
Explanation. At index 2, the element 20 is greater than both 3 (left neighbor) and 4 (right neighbor), which makes it a peak element.
[ 5, 10, 20, 15 ]
Explanation. At index 2, the element 20 is greater than 10 (left neighbor) and 15 (right neighbor), hence it's the peak.
[ 10, 7, 5, 2 ]
Explanation. The element at index 0 (10) only needs to be compared with its right neighbor (7). Since 10 is greater, it's considered a peak.
[ 8 ]
Explanation. With only one element in the array, that element is trivially a peak.
Follow-up: What modifications would be necessary if we needed to find all peaks instead of just one? How would the performance change?
The input array will have a length of at least 1. Each element in the array will be an integer.
- Views
- 3