Checking for centrally peaked arrays in JavaScript


Problem

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

Our function should check whether the input array is a centrally peaked array or not. If it is a centrally peaked array, we should return true, false otherwise.

The conditions for being a centrally peaked array are −

  • 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]

For example, if the input to the function is −

const arr = [2, 6, 7, 9, 5, 3, 1];

Then the output should be −

const output = true;

Output Explanation

Because the array peaks at 9.

Example

The code for this will be −

 Live Demo

const arr = [2, 6, 7, 9, 5, 3, 1];
const isCentrallyPeaked = (arr = []) => {
   let ind = undefined;
   for (let i = 1; i <= arr.length - 1; i++) {
      if (ind === undefined) {
         if (arr[i] < arr[i - 1]) {
            ind = i - 1
         } else if (arr[i] === arr[i - 1]) {
            return false
         }
      } else if (arr[i] >= arr[i - 1]) {
         return false
      }
   }
   return ind > 0 && ind < arr.length - 1
};
console.log(isCentrallyPeaked(arr));

Output

And the output in the console will be −

true

Updated on: 09-Apr-2021

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements