Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the middle index in the binary search loop.
DSA Rust
let mut left = 0; let mut right = arr.len() as i32 - 1; while left <= right { let mid = [1]; // rest of the code }
Attempts:
3 left
💡 Hint
Common Mistakes
Using left + right without dividing by 2 causes index out of range.
Subtracting indices instead of averaging.
✗ Incorrect
The middle index is calculated as the average of left and right indices: (left + right) / 2.
2fill in blank
mediumComplete the code to compare the middle element with the target value.
DSA Rust
if arr[mid as usize] [1] target { return Some(mid as usize); } else if arr[mid as usize] < target { left = mid + 1; } else { right = mid - 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or < instead of == causes wrong matches.
Using != leads to incorrect logic.
✗ Incorrect
We check if the middle element equals the target to find the element.
3fill in blank
hardFix the error in updating the left pointer when the middle element is less than the target.
DSA Rust
if arr[mid as usize] < target { [1] = mid + 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Updating right instead of left causes infinite loop.
Assigning mid or target instead of left.
✗ Incorrect
When middle element is less than target, move left pointer to mid + 1 to search right half.
4fill in blank
hardFill both blanks to correctly update the right pointer when the middle element is greater than the target.
DSA Rust
if arr[mid as usize] > target { [1] = [2] - 1; }
Attempts:
3 left
💡 Hint
Common Mistakes
Updating left instead of right causes wrong search direction.
Using target instead of mid causes logic errors.
✗ Incorrect
When middle element is greater than target, move right pointer to mid - 1 to search left half.
5fill in blank
hardFill all three blanks to complete the iterative binary search function returning the index or None.
DSA Rust
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut left = 0;
let mut right = arr.len() as i32 - 1;
while left <= right {
let mid = [1];
if arr[mid as usize] == target {
return Some([2]);
} else if arr[mid as usize] < target {
[3] = mid + 1;
} else {
right = mid - 1;
}
}
None
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning wrong index type causes errors.
Updating wrong pointer causes infinite loops.
✗ Incorrect
Calculate mid as average, return mid as usize when found, and update left to mid + 1 when target is greater.
