0
0
DSA Typescriptprogramming~20 mins

Find Peak Element Using Binary Search in DSA Typescript - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Peak Element Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Peak Element Finder on a Simple Array
What is the output of the following TypeScript code that finds a peak element index in the array?
DSA Typescript
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;
}

const arr = [1, 3, 20, 4, 1, 0];
console.log(findPeakElement(arr));
A3
B2
C1
D5
Attempts:
2 left
💡 Hint
Trace the binary search steps comparing mid and mid+1 elements.
🧠 Conceptual
intermediate
1:30remaining
Understanding Peak Element Definition
Which of the following best describes a peak element in an array?
AAn element that is smaller than its neighbors.
BAn element that is the maximum in the entire array.
CAn element that is greater than its immediate neighbors.
DAn element that appears more than once in the array.
Attempts:
2 left
💡 Hint
Think about local maximums.
🔧 Debug
advanced
2:00remaining
Identify the Error in Peak Element Binary Search
What error will the following TypeScript code produce when run?
DSA Typescript
function findPeak(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 - 1;
    } else {
      left = mid + 1;
    }
  }
  return left;
}

console.log(findPeak([1, 2, 3, 4]));
AReturns 3
BReturns 2
CInfinite loop
DRuntime error: Index out of bounds
Attempts:
2 left
💡 Hint
Check the condition when accessing nums[mid + 1].
Predict Output
advanced
2:00remaining
Output of Peak Element Finder on Strictly Increasing Array
What is the output of the following TypeScript code when the input array is strictly increasing?
DSA Typescript
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;
}

const arr = [1, 2, 3, 4, 5, 6];
console.log(findPeakElement(arr));
A5
B0
C3
D6
Attempts:
2 left
💡 Hint
In a strictly increasing array, the peak is at the end.
🚀 Application
expert
2:30remaining
Number of Peak Elements in a Given Array
Given the array [1, 3, 2, 4, 1, 0, 5], how many peak elements does it contain?
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count elements greater than neighbors.