0
0
DSA Javascriptprogramming~3 mins

Why Find Peak Element Using Binary Search in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find the tallest mountain without climbing every hill?

The Scenario

Imagine you have a long list of numbers representing mountain heights along a trail. You want to find a peak, a mountain taller than its neighbors, but checking each mountain one by one is tiring and slow.

The Problem

Checking each mountain manually means walking the entire trail, which takes a lot of time and effort. It's easy to make mistakes or miss the peak if you get tired or distracted.

The Solution

Using binary search, you can quickly jump to the middle mountain and decide which side to explore next, cutting the search area in half each time. This way, you find a peak much faster without checking every mountain.

Before vs After
Before
function findPeak(nums) {
  for (let i = 0; i < nums.length; i++) {
    if ((i === 0 || nums[i] > nums[i - 1]) && (i === nums.length - 1 || nums[i] > nums[i + 1])) {
      return i;
    }
  }
  return -1;
}
After
function findPeak(nums) {
  let left = 0;
  let right = nums.length - 1;
  while (left < right) {
    let mid = Math.floor((left + right) / 2);
    if (nums[mid] < nums[mid + 1]) {
      left = mid + 1;
    } else {
      right = mid;
    }
  }
  return left;
}
What It Enables

This method lets you find a peak element in a large list quickly and efficiently, saving time and effort.

Real Life Example

Finding the highest point in a hiking trail map quickly without checking every single point.

Key Takeaways

Manual search checks every element, which is slow.

Binary search cuts the search area in half each step.

Efficiently finds a peak without scanning the whole list.