Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Find Peak Element Using Binary Search
Start with low=0, high=n-1
↓
Calculate mid = (low+high)//2
↓
Compare nums[mid
↓
mid
↓
Move high = mid
↓
Repeat until low == high
↓
Return low as peak index
We repeatedly check the middle element and compare it with its right neighbor. If middle is greater, we move left; else, we move right. This narrows down to a peak element.
Execution Sample
DSA Javascript
function findPeakElement(nums) {
  let low = 0, high = nums.length - 1;
  while (low < high) {
    let mid = Math.floor((low + high) / 2);
    if (nums[mid] > nums[mid + 1]) high = mid;
    else low = mid + 1;
  }
  return low;
}
This code finds a peak element index in the array using binary search by comparing mid and mid+1 elements.
Execution Table
StepOperationlowhighmidCompare nums[mid] and nums[mid+1]Pointer ChangesCurrent Search RangePeak Candidate
1Initialize05---[1, 3, 20, 4, 1, 0]-
2Calculate mid052nums[2]=20 > nums[3]=4high = mid = 2[1, 3, 20]Index 2
3Calculate mid021nums[1]=3 < nums[2]=20low = mid + 1 = 2[20]Index 2
4low == high22---[20]Index 2 (peak found)
💡 low equals high at index 2, peak element found at nums[2] = 20
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4 (Final)
low0022
high5222
mid-21-
Key Moments - 3 Insights
Why do we compare nums[mid] with nums[mid+1] instead of nums[mid-1]?
Comparing nums[mid] with nums[mid+1] helps decide which side has a peak. If nums[mid] > nums[mid+1], peak lies on left including mid (see step 2). This avoids out-of-bound errors and ensures progress.
Why does the loop stop when low equals high?
When low equals high, the search range narrows to one element, which must be a peak (step 4). No further division is possible, so we return low.
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 by comparing neighbors (see steps 2 and 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'mid' at step 3?
A1
B2
C0
D3
💡 Hint
Check the 'mid' column in the execution_table row for step 3.
At which step does the condition nums[mid] > nums[mid+1] become true?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Compare nums[mid] and nums[mid+1]' column in the execution_table.
If nums[mid] was less than nums[mid+1] at step 2, what would happen to 'low'?
Alow would stay the same
Blow would become mid
Clow would become mid + 1
Dlow would become high
💡 Hint
Refer to the 'Pointer Changes' column in step 2 of the execution_table.
Concept Snapshot
Find Peak Element Using Binary Search:
- Use two pointers: low=0, high=n-1
- While low < high:
  - mid = (low + high) // 2
  - If nums[mid] > nums[mid+1], move high = mid
  - Else move low = mid + 1
- When low == high, return low 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 low and high pointers at the ends. We calculate mid and compare nums[mid] with nums[mid+1]. If nums[mid] is greater, the peak is on the left side including mid, so we move high to mid. Otherwise, the peak is on the right side, so we move low to mid + 1. We repeat until low equals high, which is the peak index. This method efficiently narrows down the search space by half each time.

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. The smallest element in the array
C. The first element of the array
D. An element equal to its neighbors

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 one side if at the boundary).
  2. Step 2: Compare options with the definition

    Only An element that is greater than its neighbors matches this definition exactly.
  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 smallest or equal [OK]
Common Mistakes:
  • Thinking peak means smallest element
  • Confusing peak with first or last element
  • Assuming peak equals neighbors
2. Which of the following is the correct way to calculate the middle index mid in binary search in JavaScript?
easy
A. const mid = (left + right) / 2;
B. const mid = Math.ceil((left + right) / 2);
C. const mid = Math.floor((left + right) / 2);
D. const mid = left + right / 2;

Solution

  1. Step 1: Understand integer division in JavaScript

    JavaScript division returns a float, so we use Math.floor to get an integer index.
  2. Step 2: Check each option

    const mid = Math.floor((left + right) / 2); uses Math.floor on the average of left and right, which is correct for binary search.
  3. Final Answer:

    const mid = Math.floor((left + right) / 2); -> Option C
  4. Quick Check:

    Use Math.floor for integer mid index [OK]
Hint: Use Math.floor((left + right) / 2) for mid index [OK]
Common Mistakes:
  • Not using Math.floor causes float index
  • Using only division without parentheses
  • Incorrect operator precedence in calculation
3. What will be the output of the following code snippet?
function findPeak(nums) {
  let left = 0, 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;
}

console.log(findPeak([1, 3, 2, 4, 1]));
medium
A. 3
B. 1
C. 2
D. 0

Solution

  1. Step 1: Trace the binary search steps on array [1,3,2,4,1]

    Initial left=0, right=4. mid=2 (value=2). Compare nums[2]=2 and nums[3]=4. Since 2 < 4, left=mid+1=3.
  2. Step 2: Next iteration with left=3, right=4

    mid=3 (value=4). Compare nums[3]=4 and nums[4]=1. Since 4 > 1, right=mid=3.
  3. Step 3: Loop ends as left=right=3

    Return left=3, which is index of peak element 4.
  4. Final Answer:

    3 -> Option A
  5. Quick Check:

    Peak index = 3 [OK]
Hint: Compare mid and mid+1 to decide left or right [OK]
Common Mistakes:
  • Returning value instead of index
  • Not updating left or right correctly
  • Confusing mid calculation
4. Identify the bug in this binary search code to find a peak element:
function findPeak(nums) {
  let left = 0, right = nums.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (nums[mid] < nums[mid + 1]) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return left;
}
medium
A. The comparison should be nums[mid] > nums[mid + 1] instead of <.
B. The mid calculation is incorrect.
C. The return statement should return right instead of left.
D. The loop condition should be left < right instead of <=.

Solution

  1. Step 1: Analyze the loop condition

    The loop uses left <= right, which can cause mid+1 to go out of bounds when mid = right.
  2. Step 2: Correct loop condition for safe mid+1 access

    Changing to left < right ensures mid+1 is always valid inside the loop.
  3. Final Answer:

    The loop condition should be left < right instead of <=. -> Option D
  4. Quick Check:

    Loop condition left < right avoids out-of-bounds [OK]
Hint: Use left < right to avoid mid+1 overflow [OK]
Common Mistakes:
  • Using <= causes index out of range error
  • Changing mid calculation unnecessarily
  • Returning wrong index
5. Given a strictly increasing then strictly decreasing array nums, how can you modify the binary search to find the peak element efficiently?
Choose the best approach.
hard
A. Use binary search comparing nums[mid] and nums[mid-1], move left or right accordingly.
B. Use binary search comparing nums[mid] and nums[mid+1], move left or right accordingly.
C. Scan the array linearly from start to find the maximum element.
D. Sort the array first, then pick the middle element.

Solution

  1. Step 1: Understand the array shape

    The array increases then decreases, so the peak is the maximum element where nums[mid] > nums[mid+1].
  2. Step 2: Use binary search comparing nums[mid] and nums[mid+1]

    If nums[mid] > nums[mid+1], move right pointer to mid; else move left pointer to mid+1.
  3. Step 3: Avoid linear scan or sorting

    Linear scan is O(n), sorting changes order and is unnecessary.
  4. Final Answer:

    Use binary search comparing nums[mid] and nums[mid+1], move left or right accordingly. -> Option B
  5. Quick Check:

    Compare mid and mid+1 for peak in bitonic array [OK]
Hint: Compare mid and mid+1 to find peak in bitonic array [OK]
Common Mistakes:
  • Using linear scan instead of binary search
  • Sorting array destroys peak property
  • Comparing mid and mid-1 incorrectly
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