852. Peak Index in a Mountain Array (Solution || Leetcode Easy|| Java)

Palakkgoyal
2 min readOct 28, 2022

--

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.

SOLUTION:

class Solution {
public int peakIndexInMountainArray(int[] arr) {
int start = 0;
int end = arr.length — 1;

while(start <= end){
int mid = start + (end — start)/2;

//As the element we are searching for is the highest element in the array, so the element which is greaater than both preceding and later element is our answewr
if(arr[mid] > arr[mid + 1] && arr[mid] > arr[mid — 1]){
return mid;
}

//if element of mid is greater than element of mid + 1 it means that we are the asscending part of the array, so, move the start point toward pivot(the point from where the array start descending)
else if(arr[mid] < arr[mid + 1]){
start = mid + 1;
}else{
end = mid;
}
}

return start;
}
}

TIME COMPLEXITY:- O(log(arr.length))

SPACE COMPLEXITY:- O(1)

Thank you for reading. If you have any queries, please let me now in the comment section

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet