What if you could find the highest hill without climbing them all?
Why Find Peak Element Using Binary Search in DSA Typescript?
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.
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.
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.
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;
}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;
}This method lets you find a peak quickly even in very large lists, saving time and effort.
Finding the highest point in a mountain range using fewer steps, or locating a local maximum in stock prices efficiently.
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.