Peak Index In Mountain Array
find the peak or pivot element in the mountain array
class Solution {public:
// Function to find the peak or pivot element in the mountain array int find_pivot(vector<int> v) { int s = 0, e = v.size() - 1; // Initialize start (s) and end (e) indices int mid = (s + e) / 2; // Calculate the middle index
// Binary search loop while (s < e) { if (v[mid] < v[mid + 1]) { // If mid element is smaller than the next one s = mid + 1; // Move the start to the right (look for a larger element) } else { // If mid element is larger than the next one e = mid; // Move the end to the left (since mid could be the peak) }
mid = (s + e) / 2; // Recalculate the middle index } return s; // The start and end will converge to the peak index }
// Main function that calls find_pivot to get the peak index int peakIndexInMountainArray(vector<int>& arr) { return find_pivot(arr); // Find and return the peak index }};
Example
For arr = {0, 2, 4, 6, 3, 1}:
- Initial state:
s = 0
,e = 5
,mid = (0 + 5) / 2 = 2
.v[mid] = 4
, andv[mid + 1] = 6
.- Since
v[mid] < v[mid + 1]
, moves = mid + 1 = 3
.
- Next iteration:
s = 3
,e = 5
,mid = (3 + 5) / 2 = 4
.v[mid] = 3
, andv[mid + 1] = 1
.- Since
v[mid] > v[mid + 1]
, movee = mid = 4
.
- Next iteration:
s = 3
,e = 4
,mid = (3 + 4) / 2 = 3
.v[mid] = 6
, andv[mid + 1] = 3
.- Since
v[mid] > v[mid + 1]
, movee = mid = 3
.
- Final state:
s = e = 3
.- The loop exits, and the peak index
3
is returned.