Challenge - 5 Problems
Peak Element Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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));Attempts:
2 left
💡 Hint
Trace the binary search steps comparing mid and mid+1 elements.
✗ Incorrect
The function uses binary search to find a peak element index. For the array [1, 3, 20, 4, 1, 0], the peak is at index 2 (value 20) because it is greater than its neighbors.
🧠 Conceptual
intermediate1:30remaining
Understanding Peak Element Definition
Which of the following best describes a peak element in an array?
Attempts:
2 left
💡 Hint
Think about local maximums.
✗ Incorrect
A peak element is one that is greater than its neighbors, not necessarily the maximum in the whole array.
🔧 Debug
advanced2: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]));Attempts:
2 left
💡 Hint
Check the condition when accessing nums[mid + 1].
✗ Incorrect
The code accesses nums[mid + 1] without checking if mid + 1 is within array bounds, causing a runtime error when mid is the last index.
❓ Predict Output
advanced2: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));Attempts:
2 left
💡 Hint
In a strictly increasing array, the peak is at the end.
✗ Incorrect
Since the array is strictly increasing, the last element is the peak. The function returns index 5.
🚀 Application
expert2: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?
Attempts:
2 left
💡 Hint
Count elements greater than neighbors.
✗ Incorrect
Peak elements are at indices 1 (3), 3 (4), and 6 (5). Total 3 peaks.