Finding peak of a centrally peaked array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Centrally Peaked Array

We call an array arr a centrally peaked array 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]

Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

The input array is a centrally peaked array. Our function is supposed to return the peak index of this centrally peaked array.

For example, if the input to the function is

Input

const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];

Output

const output = 4;

Output Explanation

Because the element at index 4 (15) is the peak element of this array.

Example

Following is the code −

 Live Demo

const arr = [4, 6, 8, 12, 15, 11, 7, 4, 1];
const findPeak = (arr = []) => {
   if(arr.length < 3) {
      return -1
   }
   const helper = (low, high) => {
      if(low > high) {
         return -1
      }
      const middle = Math.floor((low + high) / 2)
      if(arr[middle] <= arr[middle + 1]) {
         return helper(middle + 1, high)
      }
      if(arr[middle] <= arr[middle - 1]) {
         return helper(low, middle - 1)
      }
      return middle
   }
   return helper(0, arr.length - 1)
};
console.log(findPeak(arr));

Output

4
raja
Published on 24-Apr-2021 09:42:13
Advertisements