LeetCode Solutions

852. Peak Index in a Mountain Array

Time: $O(\log n)$

Space: $O(1)$

			

class Solution {
 public:
  int peakIndexInMountainArray(vector<int>& arr) {
    int l = 0;
    int r = arr.size() - 1;

    while (l < r) {
      const int m = (l + r) / 2;
      if (arr[m] < arr[m + 1])
        l = m + 1;
      else
        r = m;
    }

    return l;
  }
};
			

class Solution {
  public int peakIndexInMountainArray(int[] arr) {
    int l = 0;
    int r = arr.length - 1;

    while (l < r) {
      final int m = (l + r) / 2;
      if (arr[m] < arr[m + 1])
        l = m + 1;
      else
        r = m;
    }

    return l;
  }
}
			

class Solution:
  def peakIndexInMountainArray(self, arr: List[int]) -> int:
    l = 0
    r = len(arr) - 1

    while l < r:
      m = (l + r) // 2
      if arr[m] < arr[m + 1]:
        l = m + 1
      else:
        r = m

    return l