Peak index in Mountain Array
Peak Index in a Mountain Array
Binary Search
Problem Statement:
You are given an integer array arr
that represents a mountain array. Your task is to find the peak index i
, such that:
arr[i - 1] < arr[i]
arr[i] > arr[i + 1]
Algorithm:
- Initialize two pointers,
low
andhigh
, representing the bounds of the array. - Perform binary search:
- Calculate the mid-point
mid = low + (high - low) / 2
to avoid overflow. - Check if
mid
is the peak:arr[mid]
must be greater than its left neighborarr[mid - 1]
(or it's the first element).arr[mid]
must also be greater than its right neighborarr[mid + 1]
(or it's the last element).
- If
arr[mid]
is less thanarr[mid + 1]
, move thelow
pointer tomid + 1
. - Otherwise, move the
high
pointer tomid - 1
.
- Calculate the mid-point
- The loop ends when the peak is found.
Complexity:
Time: O(log n) – The binary search reduces the search space by half in each iteration.
Space: O(1) – No additional space is required.
Java Implementation:
public int peakIndexInMountainArray(int[] arr) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate mid-point to avoid overflow
// Check if mid is the peak
// A peak satisfies: (1) greater than left (or at boundary) and (2) greater than right (or at boundary)
if ((mid == 0 || arr[mid] > arr[mid - 1]) && (mid == arr.length - 1 || arr[mid] > arr[mid + 1]))
return mid;
// If the right neighbor is greater, the peak lies to the right
if (mid < arr.length - 1 && arr[mid] < arr[mid + 1])
low = mid + 1; // Move the low pointer to the right
else
high = mid - 1; // Otherwise, the peak lies to the left
}
// Should not reach here since a peak is guaranteed
return -1;
}
Python Implementation:
def peakIndexInMountainArray(arr):
low, high = 0, len(arr) - 1
while low <= high:
mid = low + (high - low) // 2 # Calculate mid-point to avoid overflow
# Check if mid is the peak
if (mid == 0 or arr[mid] > arr[mid - 1]) and (mid == len(arr) - 1 or arr[mid] > arr[mid + 1]):
return mid
# If the right neighbor is greater, move low to mid + 1
if mid < len(arr) - 1 and arr[mid] < arr[mid + 1]:
low = mid + 1
else:
high = mid - 1
# Should not reach here since a peak is guaranteed
return -1
C++ Implementation:
int peakIndexInMountainArray(vector& arr) {
int low = 0, high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate mid-point to avoid overflow
// Check if mid is the peak
if ((mid == 0 || arr[mid] > arr[mid - 1]) && (mid == arr.size() - 1 || arr[mid] > arr[mid + 1]))
return mid;
// If the right neighbor is greater, move low to mid + 1
if (mid < arr.size() - 1 && arr[mid] < arr[mid + 1])
low = mid + 1;
else
high = mid - 1;
}
// Should not reach here since a peak is guaranteed
return -1;
}