Peak Index in a Mountain Array – Leetcode Solution

In this post, we are going to solve the 852. Peak Index in a Mountain Array problem of Leetcode. This problem 852. Peak Index in a Mountain Array is a Leetcode medium level problem. Let’s see the code, 852. Peak Index in a Mountain Array – Leetcode Solution.

Problem

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.

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.

Now, let’s see the code of 852. Peak Index in a Mountain Array – Leetcode Solution.

Peak Index in a Mountain Array – Leetcode Solution

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

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

        while(s < e){
            int mid = s - ( s - e)/2;
            int mid2 = mid+1;
            if(arr[mid] < arr[mid2]) {
                s = mid2;
            }else {
                e = mid;
            }
            
        }
        return s;
    }
}

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

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

        while(s < e){
            int mid = s - ( s - e)/2;
            int mid2 = mid+1;
            if(arr[mid] < arr[mid2]) {
                s = mid2;
            }else {
                e = mid;
            }
            
        }
        return s;
    }
};

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

class Solution(object):
    def peakIndexInMountainArray(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        beg, end = 0, len(arr) - 1
        while beg < end:
            mid = (beg + end)//2
            if arr[mid] < arr[mid + 1]:
                beg = mid + 1
            else:
                end = mid

        return end
        

Note: This problem 852. Peak Index in a Mountain Array is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *