Skip to content

882. Peak Index In A Mountain Array

Array Binary Search

Problem - Peak Index In A Mountain Array

Medium

You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.

Return the index of the peak element.

Your task is to solve it in O(log(n)) time complexity.

 

Example 1:

Input: arr = [0,1,0]

Output: 1

Example 2:

Input: arr = [0,2,1,0]

Output: 1

Example 3:

Input: arr = [0,10,5,2]

Output: 1

 

Constraints:

  • 3 <= arr.length <= 105
  • 0 <= arr[i] <= 106
  • arr is guaranteed to be a mountain array.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * @param {number[]} arr
 * @return {number}
 */
var peakIndexInMountainArray = function(arr) {
    let bot = 0
    let top = arr.length - 1
    let mid

    while (bot < top){
        mid = bot + Math.floor((top - bot)/2)
        if (arr[mid] >= arr[mid+1]){
            top = mid
        } else{
            bot = mid + 1
        }
    }

    return bot


};

Submission Stats:

  • Runtime: 69 ms (2.20%)
  • Memory: 51.4 MB (100.00%)