Finding element greater than its adjacent elements in JavaScript

JavascriptWeb DevelopmentFront End Technology

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

The function should find and return one such number from the array which is greater than both, the number on its immediate right and the number on its immediate left. If there exists more than one such element in the array, our function should return any one of them.

For example −

If the input array is −

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

Then the output should be −

const output = 9;

Since the question demands finding the peak element, we can use a tweaked version of the binary search algorithm.

The steps for the same will be −

  • Look at any element.

  • If the next element and the previous elements are both less than the current, we find a solution, then return the index of current.

  • If the next element is greater than the current, there must be a peak to the right, look recursively to the right.

  • If the previous element is greater than current, there must be a peak to the left, look recursively to the left.

Example

Following is the code −

const arr = [3, 6, 7, 9, 8, 2, 5];
const greaterThanAdjacent = (arr = [], start = 0, end = arr.length) => {
   let mid = start + Math.floor((end - start) / 2);
   let curr = arr[mid];
   let prev = mid-1 < 0 ? -Infinity : arr[mid-1];
   let next = mid+1 > arr.length-1 ? -Infinity : arr[mid+1];
   if (curr > prev && curr > next){
      return arr[mid];
   }
   if (curr < next){
      return greaterThanAdjacent(arr, mid+1, end);
   }
   if (curr > next){
      return greaterThanAdjacent(arr, start, mid-1);
   }
   return null;
};
console.log(greaterThanAdjacent(arr));

Output

Following is the console output −

9
raja
Published on 20-Jan-2021 06:35:05
Advertisements