0
0
DSA Typescriptprogramming~10 mins

Find Peak Element Using Binary Search in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the middle index for binary search.

DSA Typescript
let mid = Math.[1]((left + right) / 2);
Drag options to blanks, or click blank then click option'
Aceil
Bfloor
Cround
Dtrunc
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.ceil causes index to go out of range sometimes.
Using Math.round can cause uneven splits.
2fill in blank
medium

Complete the condition to check if mid element is a peak.

DSA Typescript
if ((mid === 0 || nums[mid] > nums[mid - 1]) && (mid === nums.length - 1 || nums[mid] > nums[[1]])) {
Drag options to blanks, or click blank then click option'
Anums.length
Bmid - 1
Cmid
Dmid + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using mid - 1 instead of mid + 1 causes wrong comparison.
Using nums.length as index causes out of bounds error.
3fill in blank
hard

Fix the error in updating the left pointer when mid element is less than the next element.

DSA Typescript
if (nums[mid] < nums[mid + 1]) {
    left = [1];
} else {
    right = mid;
}
Drag options to blanks, or click blank then click option'
Amid + 1
Bmid
Cleft + 1
Dright - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Setting left to mid causes infinite loop when mid doesn't change.
Using right - 1 is wrong direction.
4fill in blank
hard

Fill both blanks to complete the binary search loop condition and return statement.

DSA Typescript
while ([1] < [2]) {
    // binary search steps
}
return left;
Drag options to blanks, or click blank then click option'
Aleft
Bright
Cmid
Dnums.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using mid in loop condition causes errors.
Returning right instead of left can be confusing but works; here we use left.
5fill in blank
hard

Fill all three blanks to complete the function signature, initialize pointers, and return the peak index.

DSA Typescript
function findPeakElement([1]: number[]): number {
    let [2] = 0;
    let right = nums.length - 1;
    while (left < right) {
        let mid = Math.floor((left + right) / 2);
        if (nums[mid] < nums[mid + 1]) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return [3];
}
Drag options to blanks, or click blank then click option'
Anums
Bleft
Dright
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter name causes errors.
Returning right instead of left is possible but inconsistent here.