852. Peak Index in a Mountain Array

An array arr a mountain if the following properties hold:

  • arr.length >= 3
  • There exists some i 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]

Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

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




def peakIndexInMountainArray(self, arr: List[int]):
       
    lo, hi = 0, len(arr) - 1
   
    while lo < hi:
        mid = (lo + hi) // 2
       
        if arr[mid + 1] > arr[mid]: # Still increasing
            lo = mid + 1
        else:
            hi = mid # Notice it's not mid - 1,
   

    return lo # hi also works 

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break