852. Peak Index in a Mountain Array LeetCode Solution

In this guide, you will get 852. Peak Index in a Mountain Array LeetCode Solution with the best time and space complexity. The solution to Peak Index in a Mountain Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Peak Index in a Mountain Array solution in C++
  4. Peak Index in a Mountain Array solution in Java
  5. Peak Index in a Mountain Array solution in Python
  6. Additional Resources
852. Peak Index in a Mountain Array LeetCode Solution image

Problem Statement of Peak Index in a Mountain Array

You are given an integer mountain array arr of length n where the values increase to a peak element and then decrease.
Return the index of the peak element.
Your task is to solve it in O(log(n)) time complexity.

Example 1:

Input: arr = [0,1,0]
Output: 1

Example 2:

Input: arr = [0,2,1,0]
Output: 1

Example 3:

Input: arr = [0,10,5,2]
Output: 1

Constraints:

3 <= arr.length <= 105
0 <= arr[i] <= 106
arr is guaranteed to be a mountain array.

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

852. Peak Index in a Mountain Array LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

852. Peak Index in a Mountain Array LeetCode Solution in Java

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;
  }
}
// code provided by PROGIEZ

852. Peak Index in a Mountain Array LeetCode Solution in Python

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
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.