Solution: 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: Brute Force
One simple way to solve this problem is to start from the beginning, compare each element with its neighbors, and just return the peak element wherever you find it in the array.
There must always be one peak element in an array with distinct elements, but it’s possible that the array is sorted in ascending order like this:
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 . Can we do better?
Solution #2: Efficient
Using divide and conquer, we can speed up the whole process. Have a look at the solution given below:
Start with the middle element of the array (Line 8)
- Compare the element with its neighbors.
- If the middle element is not smaller than any of its neighbors, then we return it. (Line 13)
- If the middle element is smaller than its left neighbor, then there is always a peak in the left half. (Line 18)
- If the middle element is smaller than its right neighbor, then there is always a