Find the peak element in array - DSA in JavaScript

Question:

Solution:

Basic approach

 // Edge case: empty or one-element array
    if (n === 0) return -1;
    if (n === 1) return 0;

    // Check first and last elements
    if (arr[0] > arr[1]) return 0;
    if (arr[n - 1] > arr[n - 2]) return n - 1;

    // Check middle elements
    for (let i = 1; i < n - 1; i++) {
        if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
            return i;
        }
    }

    // No peak found
    return -1;
0
Subscribe to my newsletter

Read articles from Bishal Kumar Shaw directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bishal Kumar Shaw
Bishal Kumar Shaw