Leetcode 852. Peak Index in a Mountain Array
Given an array of integers arr that is strictly increasing until it reaches a peak element and then strictly decreasing, find the index of the peak element. You can assume that arr is guaranteed to be a mountain array.
A mountain array is defined as an array that:
arr.length >= 3i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]arr[i] > arr[i + 1] > ... > arr[arr.length - 1]To solve this problem efficiently, we can use binary search, given the properties of the mountain array (strictly increasing then strictly decreasing). Binary search enables us to find the peak element in O(log n) time, which is more efficient than a linear scan.
left at the start of the array and right at the end of the array.left is less than right:
mid as the middle index between left and right.arr[mid] is less than arr[mid + 1], it means the peak lies to the right side, so we shift left to mid + 1.right to mid.left equals right, we have found the peak index.This approach ensures we efficiently find the peak element in logarithmic time.
public class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 0, right = arr.length - 1;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] < arr[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
O(log n) where n is the number of elements in the array. This is because we are using binary search which divides the search space by half each iteration.O(1) since we are using a constant amount of additional space (just a couple of pointers and a mid variable).This approach is efficient and suitable for large arrays.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?