Bird
Raised Fist0
DSA Goprogramming~10 mins

Find Peak Element Using Binary Search in DSA Go - Execution Trace

Choose your learning style10 modes available
Concept Flow - Find Peak Element Using Binary Search
Start with array boundaries: left=0, right=n-1
↓
Calculate mid = (left+right)/2
↓
Compare nums[mid
↓
mid
↓
Move right boundary to mid
↓
Move left boundary to mid+1
↓
Repeat until left == right
↓
Return left as peak index
We repeatedly check the middle element and compare it with its right neighbor to decide which half contains a peak, narrowing the search until we find a peak.
Execution Sample
DSA Go
func findPeakElement(nums []int) int {
    left, right := 0, len(nums)-1
    for left < right {
        mid := (left + right) / 2
        if nums[mid] < nums[mid+1] {
            left = mid + 1
        } else {
            right = mid
        }
    }
    return left
}
This code finds a peak element index in the array using binary search by comparing middle elements with their neighbors.
Execution Table
StepOperationleftrightmidCompare nums[mid] < nums[mid+1]ActionVisual State (nums with pointers)
1Initialize05---nums=[1, 3, 20, 4, 1, 0], left=0, right=5
2Calculate mid05220 < 4? Falseright = midnums=[1, 3, 20, 4, 1, 0], left=0, right=2
3Calculate mid0213 < 20? Trueleft = mid + 1nums=[1, 3, 20, 4, 1, 0], left=2, right=2
4Check left < right22--left == right, stopnums=[1, 3, 20, 4, 1, 0], peak at index 2
💡 left equals right at index 2, which is a peak element
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4 (final)
left0022
right5222
mid-211 (last calculated)
Key Moments - 3 Insights
Why do we compare nums[mid] with nums[mid+1] and not nums[mid-1]?
Comparing nums[mid] with nums[mid+1] helps decide if the peak is on the right or left side. If nums[mid] < nums[mid+1], the peak must be right of mid, so we move left boundary. This is shown in execution_table row 2 and 3.
Why does the loop stop when left equals right?
When left equals right, it means the search space is narrowed down to one element, which must be a peak. This is the exit condition shown in execution_table row 4.
What if the array has multiple peaks?
This method finds any one peak, not necessarily the highest. The binary search narrows to a local peak as shown by the pointer movements in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the value of mid and what comparison is made?
Amid=3, compare nums[3]=4 < nums[4]=1
Bmid=1, compare nums[1]=3 < nums[2]=20
Cmid=2, compare nums[2]=20 < nums[3]=4
Dmid=0, compare nums[0]=1 < nums[1]=3
💡 Hint
Check the 'mid' and 'Compare nums[mid] < nums[mid+1]' columns in execution_table row 2
At which step does the left pointer move to mid+1?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table row 3
If nums[mid] was always greater than nums[mid+1], what would happen to the pointers?
Aright would keep moving to mid
Bleft would keep increasing
Cleft and right would not change
Dloop would never end
💡 Hint
Refer to the 'Action' column where nums[mid] < nums[mid+1] is false, right is set to mid
Concept Snapshot
Find Peak Element Using Binary Search:
- Use two pointers: left=0, right=n-1
- While left < right:
  - mid = (left+right)//2
  - If nums[mid] < nums[mid+1], move left to mid+1
  - Else move right to mid
- When left == right, return left as peak index
- Works because peak must exist where slope changes
Full Transcript
This concept uses binary search to find a peak element in an array. We start with two pointers at the ends of the array. We calculate the middle index and compare the middle element with its right neighbor. If the middle element is less than its right neighbor, the peak lies to the right, so we move the left pointer to mid+1. Otherwise, the peak lies to the left or at mid, so we move the right pointer to mid. We repeat this until left equals right, which is the peak index. This method efficiently narrows down the search space by half each time, ensuring a peak is found quickly.

Practice

(1/5)
1. What is a peak element in an array when using binary search to find it?
easy
A. An element that is greater than its neighbors
B. An element that is smaller than its neighbors
C. The first element of the array
D. The last element of the array

Solution

  1. Step 1: Understand the definition of a peak element

    A peak element is one that is strictly greater than its neighbors on both sides (or only one side if at the boundary).
  2. Step 2: Apply this to binary search context

    Binary search finds such an element by comparing middle elements with neighbors to decide which half to search next.
  3. Final Answer:

    An element that is greater than its neighbors -> Option A
  4. Quick Check:

    Peak element = greater than neighbors [OK]
Hint: Peak element is bigger than neighbors, not smaller [OK]
Common Mistakes:
  • Thinking peak is smallest element
  • Confusing peak with first or last element always
  • Ignoring boundary conditions
2. Which Go code snippet correctly initializes the binary search boundaries to find a peak element in array nums?
easy
A. left, right := 1, len(nums)
B. left, right := 0, len(nums) - 1
C. left, right := 0, len(nums)
D. left, right := 1, len(nums) - 1

Solution

  1. Step 1: Identify valid index range for array in Go

    Array indices in Go start at 0 and end at len(nums)-1, so boundaries must be set accordingly.
  2. Step 2: Check each option for correct boundary initialization

    left, right := 0, len(nums) - 1 correctly sets left=0 and right=len(nums)-1, covering full array indices.
  3. Final Answer:

    left, right := 0, len(nums) - 1 -> Option B
  4. Quick Check:

    Array indices 0 to len-1 [OK]
Hint: Array indices go from 0 to length-1 in Go [OK]
Common Mistakes:
  • Setting right to len(nums) (out of range)
  • Starting left at 1 and missing first element
  • Using negative indices
3. What will be the output index of the peak element for the array nums := []int{1, 3, 20, 4, 1, 0} using binary search peak finding?
medium
A. 3
B. 1
C. 2
D. 0

Solution

  1. Step 1: Identify peak candidates in the array

    Array: [1, 3, 20, 4, 1, 0]. 20 at index 2 is greater than neighbors 3 and 4, so it's a peak.
  2. Step 2: Confirm binary search finds index 2

    Binary search compares mid elements and moves left or right until it finds peak at index 2.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Peak at index 2 with value 20 [OK]
Hint: Peak is local max, here 20 at index 2 [OK]
Common Mistakes:
  • Choosing first or last element incorrectly
  • Confusing index with value
  • Not checking both neighbors
4. Given the following Go code snippet to find a peak element, what is the bug?
func findPeak(nums []int) int {
    left, right := 0, len(nums)-1
    for left < right {
        mid := (left + right) / 2
        if nums[mid] < nums[mid+1] {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }
    return left
}
medium
A. The right boundary update should be right = mid, not mid - 1
B. The left boundary update should be left = mid, not mid + 1
C. The loop condition should be left <= right
D. The function should return right instead of left

Solution

  1. Step 1: Analyze the binary search boundary updates

    When nums[mid] >= nums[mid+1], peak is at mid or to the left, so right should be set to mid, not mid - 1 to avoid skipping mid.
  2. Step 2: Identify impact of wrong right update

    Using right = mid - 1 skips mid, possibly missing the peak element.
  3. Final Answer:

    The right boundary update should be right = mid, not mid - 1 -> Option A
  4. Quick Check:

    Right boundary must include mid [OK]
Hint: Use right = mid to keep mid in search space [OK]
Common Mistakes:
  • Setting right = mid - 1 and skipping mid
  • Changing left incorrectly
  • Wrong loop condition causing infinite loop
5. You have an array nums := []int{10, 20, 15, 2, 23, 90, 67}. Using binary search to find a peak element, which index will be returned and why?
hard
A. 1, because 20 is a peak greater than neighbors 10 and 15
B. 0, because first element is always a peak
C. 6, because last element is always a peak
D. 5, because 90 is a peak greater than neighbors 23 and 67

Solution

  1. Step 1: Identify all peak candidates in the array

    Array: [10, 20, 15, 2, 23, 90, 67]. Peaks are 20 at index 1 and 90 at index 5.
  2. Step 2: Understand binary search behavior

    Binary search compares mid and mid+1; it will move towards the higher peak 90 at index 5.
  3. Step 3: Confirm returned index

    Binary search will return index 5 where 90 is a peak greater than neighbors 23 and 67.
  4. Final Answer:

    5, because 90 is a peak greater than neighbors 23 and 67 -> Option D
  5. Quick Check:

    Binary search finds highest local peak at index 5 [OK]
Hint: Binary search finds any peak, often the higher one found first [OK]
Common Mistakes:
  • Assuming first or last element always peak
  • Choosing smaller peak incorrectly
  • Not understanding binary search direction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard