0
0
DSA Typescriptprogramming~3 mins

Why Find Peak Element Using Binary Search in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find the highest hill without climbing them all?

The Scenario

Imagine you have a long row of hills, and you want to find the highest hill without climbing every single one.

Checking each hill one by one takes a lot of time and effort.

The Problem

Going hill by hill is slow and tiring.

You might miss the highest hill if you get tired or lose focus.

It's like searching for a needle in a haystack by looking at every straw.

The Solution

Using binary search, you can quickly jump to the middle hill and decide which side to explore next.

This way, you skip many hills and find a peak much faster.

Before vs After
Before
function findPeakElement(nums: number[]): number {
  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 findPeakElement(nums: number[]): number {
  let left = 0;
  let right = nums.length - 1;
  while (left < right) {
    const mid = Math.floor((left + right) / 2);
    if (nums[mid] > nums[mid + 1]) right = mid;
    else left = mid + 1;
  }
  return left;
}
What It Enables

This method lets you find a peak quickly even in very large lists, saving time and effort.

Real Life Example

Finding the highest point in a mountain range using fewer steps, or locating a local maximum in stock prices efficiently.

Key Takeaways

Manual search checks every element, which is slow.

Binary search jumps smartly to find a peak faster.

This approach works well for large data sets.