Skip to content

852. Peak Index in a Mountain Array 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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])
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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])
        r = m;
      else
        l = m + 1;
    }

    return l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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]:
        r = m
      else:
        l = m + 1

    return l