code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

03 Peak Index In A Mountain Array

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const peakIndexInAMountainArray = arr => {
  let start = 0
  let end = arr.length - 1
  while (start < end) {
    const mid = Math.trunc((start + end) / 2)
    if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {
      return mid
    } else if (arr[mid] < arr[mid - 1]) {
      start = mid + 1
    } else {
      end = end - 1
    }
  }
}

console.log(peakIndexInAMountainArray([0, 2, 1, 0]))

Created 2022-03-18T13:11:19+00:00 · Edit