Solution: Find the Peak Element
This review discusses the solution of the peak element challenge in detail.
We'll cover the following...
We'll cover the following...
Solution: 1
One simple way to solve this problem is:
Explanation
- Start from the beginning, compare each element with its neighbors
- Return the peak element wherever you find it in the list
If the list 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 list.
Time complexity
This solution gives us a worst-case time complexity of .
Any better solution?
Solution: 2 (efficient)
Using divide and conquer, we can speed up the whole process. Have a look at the solution given below:
Explanation
Start with the middle element of the list Line 11
- Compare the element with its neighbors
- If the middle element is not smaller than any of its neighbors, we return it Line 14
- If the middle element is smaller than its left neighbor, there is always a peak in the left half Line 18
- If the middle element is smaller than its right neighbor, there is always a peak in the right half Line 23