algoadvance

Given an array of integers arr that is a mountain array, return the peak index in the mountain array.

A mountain array is defined as an array that:

You must solve it in O(log(n)) time complexity.

Clarifying Questions

  1. What should be returned when there are multiple peaks?
    • The problem guarantees a unique peak because of the definition of a mountain array.
  2. Are there any constraints on the values of the array elements?
    • The array elements will be integers, but no specific range is given.
  3. Can the input array have duplicate values?
    • Based on the definition of a mountain array, there should be no duplicates around the peak.

Strategy

To solve this problem efficiently in O(log(n)) time complexity, we can use a binary search approach. Here’s how:

Code

def peakIndexInMountainArray(arr: int) -> int:
    left, right = 0, len(arr) - 1
    while left < right:
        mid = (left + right) // 2
        if arr[mid] < arr[mid + 1]:
            left = mid + 1
        else:
            right = mid
    return left

Time Complexity

Try our interview co-pilot at AlgoAdvance.com