0
0
DSA Goprogramming~30 mins

Find Peak Element Using Binary Search in DSA Go - Build from Scratch

Choose your learning style9 modes available
Find Peak Element Using Binary Search
📖 Scenario: You are working with a list of numbers representing heights of hills along a trail. You want to find a hill that is taller than its neighbors, called a peak.Using a fast method called binary search, you will find one peak hill without checking every hill.
🎯 Goal: Build a Go program that finds a peak element in a list of integers using binary search.A peak element is one that is greater than its neighbors.
📋 What You'll Learn
Create a slice of integers called heights with the exact values: 1, 3, 20, 4, 1, 0
Create two integer variables left and right to hold the start and end indexes of the slice
Write a for loop that runs while left is less than right
Inside the loop, calculate the middle index mid and compare heights[mid] with heights[mid+1]
Adjust left or right based on the comparison to narrow down the peak location
After the loop ends, print the index of the peak element
💡 Why This Matters
🌍 Real World
Finding peak elements quickly is useful in signal processing, stock price analysis, and terrain mapping where you want to identify local maximum points.
💼 Career
Binary search and peak finding algorithms are common in software engineering interviews and are useful for optimizing search problems in real applications.
Progress0 / 4 steps
1
Create the heights slice
Create a slice of integers called heights with these exact values: 1, 3, 20, 4, 1, 0
DSA Go
Hint

Use heights := []int{1, 3, 20, 4, 1, 0} to create the slice.

2
Set left and right pointers
Create two integer variables called left and right. Set left to 0 and right to the last index of heights (which is 5).
DSA Go
Hint

Use left := 0 and right := len(heights) - 1.

3
Implement binary search loop to find peak
Write a for loop that runs while left < right. Inside the loop, calculate mid as (left + right) / 2. If heights[mid] is less than heights[mid+1], set left to mid + 1. Otherwise, set right to mid.
DSA Go
Hint

Use a for loop with condition left < right. Calculate mid inside the loop. Compare heights[mid] and heights[mid+1] to decide how to move left or right.

4
Print the peak element index
Print the value of left which is the index of the peak element.
DSA Go
Hint

Use fmt.Println(left) to print the peak index.