-
Notifications
You must be signed in to change notification settings - Fork 255
Mountain Peak
Sar Champagne Bielert edited this page Apr 8, 2024
·
5 revisions
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Can there be multiple peaks in the mountain array?
- No. By our definition of mountain array, there will only ever be one peak.
- What if the array is empty?
- The array will always have at least 3 elements.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop through each middle element and compare it to the element after. If it's larger than the next element, we've found the peak.
1) Loop through the middle elements of the array (skip the beginning/end)
2) Compare each element to the next element
a) If the next element is bigger, keep looking
b) If the next element is smaller, return the current element
def peak_index_in_mountain_array(arr):
for i in range(1, len(arr) - 1):
if arr[i] > arr[i + 1]:
return i