LeetCode 852: Peak Index in a Mountain Array

ArrayBinary Search

Problem Description

Explanation

To find the peak index in a mountain array in O(log(n)) time complexity, we can use a binary search approach.

  1. Initialize left and right pointers to the start and end indices of the array.
  2. While left < right: a. Calculate the mid index. b. If arr[mid] < arr[mid+1], peak must be on the right side of mid. Set left = mid + 1. c. Else, peak must be on the left side of mid. Set right = mid.
  3. Return left as the peak index.

Time complexity: O(log(n)) Space complexity: O(1)

Solutions

class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] < arr[mid + 1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}

Loading editor...