July 13, 2021 Andrey

Find Peak Element with JS

A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

An interesting challenge to solve the following problem within O(log(n)) time.

We can use the binary sort approach by checking the middle element of the array and its neighbors and following it up with either left or right side.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var findPeakElement = function(nums) {
    return rec(nums, 0, nums.length - 1);
};

var rec = function(nums, l, r) {
    let mid = Math.round((l+r) / 2);
    if (mid == l || mid == r) {
        if (l == r) return mid; // check edge case for 1 element 
        if (nums[l] > nums[r]) return l; // check edge case for 2 elements 
        else return r;
    }
    if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid+1]) {return mid;}
    else if (nums[mid - 1] > nums[mid]) {return rec(nums, l, mid - 1);}
    else if (nums[mid + 1] > nums[mid]) {return rec(nums, mid + 1, r);}
}