Published on

Javascript Solution Find Peak in an Array

Authors

Problem Overview

Given an array of integers nums find the peak number. A number nums[pos] will be peak if num[pos-1] < nums[pos] && nums[pos]>nums[pos+1].

We can assume nums[-1] = nums[n] = -∞.

Note: Multiple peak element possible return any index of those peaks.

Constraints:

1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1] for all valid i.

For exact problem visit Leetcode Link;

Sample Input Output

Input: nums = [1, 2, 3, 1]
Output: 2
Input: nums = [1, 2, 1, 3, 5, 6, 4]
Output: 5

Javascript Solution

  1. If a position mid is peak element then we will return mid.
  2. Now there are two possiblty:
    1. If nums[mid + 1]> nums[mid] then peak will be right side of mid position.
    2. If nums[mid - 1]> nums[mid] then peak will be left side of mid position.

Time Complexity: O(log(n))

/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function (nums) {
/**
* @param {number[]} arr
* @param {number} pos
* @return {boolean}
*/
const isPeak = (arr, pos) => {
return (
(pos - 1 < 0 || arr[pos] > arr[pos - 1]) && (pos + 1 >= arr.length || arr[pos] > arr[pos + 1])
)
}
let left = 0
let right = nums.length - 1
while (left <= right) {
const mid = left + Math.floor((right - left) / 2)
if (isPeak(nums, mid)) {
return mid
}
if (nums[mid] < nums[mid + 1]) {
left = mid + 1
} else {
right = mid - 1
}
}
}