Checking for centrally peaked arrays in JavaScript

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.

Conditions for Centrally Peaked Array

The conditions for being a centrally peaked array are:

  • arr.length >= 3

  • There exists some i with 0

    • arr[0]

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

true

Because the array peaks at 9 and follows the required pattern.

Example

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));
true

How It Works

The algorithm works by finding the peak index where the array transitions from increasing to decreasing:

  • It iterates through the array to find where the strictly increasing sequence ends

  • Once it finds a decreasing element, it marks the peak index

  • It then ensures all remaining elements are strictly decreasing

  • Returns false if duplicate elements are found or the peak is at the boundaries

Additional Examples

// Valid centrally peaked array
console.log(isCentrallyPeaked([1, 3, 5, 4, 2])); // true

// Invalid - duplicate elements
console.log(isCentrallyPeaked([1, 2, 2, 1])); // false

// Invalid - peak at boundary
console.log(isCentrallyPeaked([5, 4, 3, 2])); // false

// Invalid - too short
console.log(isCentrallyPeaked([1, 2])); // false
true
false
false
false

Conclusion

A centrally peaked array must have a single peak in the middle with strictly increasing elements before it and strictly decreasing elements after it. The algorithm efficiently detects this pattern in a single pass through the array.

Updated on: 2026-03-15T23:19:00+05:30

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements