Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to find the middle index in binary search.
DSA Javascript
const mid = Math.floor((low + [1]) / 2);
Attempts:
3 left
💡 Hint
Common Mistakes
Using mid before it is defined.
Using arr.length instead of high.
✗ Incorrect
The middle index is calculated by averaging low and high indices.
2fill in blank
mediumComplete the code to check if the middle element is the target.
DSA Javascript
if (arr[mid] === [1]) { return mid; }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing arr[mid] to mid index.
Comparing arr[mid] to low or high indices.
✗ Incorrect
We compare the middle element with the target value.
3fill in blank
hardFix the error in updating the low index when target is greater than middle element.
DSA Javascript
if (arr[mid] < target) { low = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting low to mid causes infinite loop.
Setting low to low + 1 misses the correct position.
✗ Incorrect
We move low to mid + 1 to search the right half excluding mid.
4fill in blank
hardFill both blanks to update high index when target is less than middle element.
DSA Javascript
if (arr[mid] > target) { high = [1]; } else { low = [2]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using high - 1 instead of mid - 1.
Using low + 1 incorrectly.
✗ Incorrect
When target is less, high moves to mid - 1; else low moves to mid + 1.
5fill in blank
hardFill all three blanks to complete the binary search function.
DSA Javascript
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + [1]) / 2);
if (arr[mid] === [2]) {
return mid;
} else if (arr[mid] < target) {
low = [3];
} else {
high = mid - 1;
}
}
return -1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variables in mid calculation.
Comparing arr[mid] to wrong variable.
Incorrectly updating low index.
✗ Incorrect
Mid is average of low and high; compare arr[mid] to target; update low to mid + 1 if target is greater.
