Solution: Peak Element
This review discusses the solution of the Peak Element Challenge in detail.
We'll cover the following...
Solution #1
One simple way to solve this problem is:
In the code above, we:
- Start from the beginning and compare each element with its neighbors.
- Return the peak element wherever it is found 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 just like this:
In this case, the peak element is at the end of the array.
Time complexity
The implementation of this solution is left for your own understanding. It gives us a worst-case time complexity of .
Can we do better?
"Solution #2: Divide and conquer (efficient)
Using divide and conquer, we can speed up the whole process. Have a look at the solution given below:
Explanation
-
Line 37: The driver calls the
findPeak(int[]array)function. -
Line 27: A helper function
findPeakRecursive(int high, int low, int size, int[]arr)is called to get the peak value. -
Line 7: The function starts with calculating the middle index of the array.
-
...