Solution: Find the Peak Element
Review various solution approaches to find the peak element in detail.
We'll cover the following...
We'll cover the following...
Solution 1
One simple way to solve this problem is the following:
Explanation
- We start from the beginning and compare each element with its neighbors.
- We return the peak element wherever we find it in the array.
If the array is sorted in an increasing order with no repetition, then the last element is always a peak element:
In this case, the peak element is at the end of the array.
Time complexity
This solution gives us a worst-case time complexity of .
Solution 2: This one’s more efficient
Using divide and conquer, we can speed up the whole process. Have a look at the solution given below:
Explanation
- We start with the middle element of the array (line 15).
- We compare the element with its neighbors.
- If the middle element is not smaller than any of its neighbors, we return it (line 18).
- If the middle element is smaller than its left neighbor, there is always a peak in the left half (line 25).
- If the middle element is smaller than its right neighbor, there is always