Skip to content

Question:

Course: Binary search, two sum and strings - chapter 6

Link: https://leetcode.com/problems/find-peak-element/

Is there a property that is getting satisfied by each array element and is monotonic?

In the first half we have elements arr[i] > arr[i-1]

In the second half, it is arr[i] < arr[i-1]

If we consider this property, do we get a 0-1 array? Yes!

Let’s understand with an example:

[1, 2, 3, 4, 3, 2]

Ignore index 0, as -1 is not a valid index. Let’s compute from 1

index = 1: Is arr[i] < arr[i-1]? No

index = 2: Is arr[i] < arr[i-1]? No

index = 3: Is arr[i] < arr[i-1]? No

index = 4: Is arr[i] < arr[i-1]? Yes

index = 5: Is arr[i] < arr[i-1]? Yes

So we get [null, 0, 0, 0, 1, 1]

Now we can do binary search on this.

class Solution {
public:
int findPeakElement(vector<int>& arr) {
int n = arr.size();
if (n == 1) {
return 0;
}
int lo = 1, hi = n - 1;
// Property arr[i] < arr[i-1]
if (arr[lo] < arr[lo-1]) {
return 0;
} else if (arr[hi] > arr[hi-1]) {
return n-1;
}
while (lo < hi - 1) {
cout<<lo<<" "<<hi<<endl;
int mid = (lo + hi) / 2;
if (arr[mid] > arr[mid-1]) {
lo = mid;
} else hi = mid;
}
return lo;
}
};