Since arr[mid] == target, function returns Some(2).
Final Answer:
Some(2) -> Option B
Quick Check:
Index of 6 in array is 2 [OK]
Hint: Check mid index value equals target first [OK]
Common Mistakes:
Off-by-one errors in mid calculation
Confusing index with value
Returning None incorrectly when target exists
4. Identify the bug in this binary search Rust code and choose the correct fix:
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut left = 0;
let mut right = arr.len();
while left <= right {
let mid = left + (right - left) / 2;
if arr[mid] == target {
return Some(mid);
} else if arr[mid] < target {
left = mid + 1;
} else {
right = mid - 1;
}
}
None
}
medium
A. Change while condition to left < right
B. Change mid calculation to (left + right) / 2 without subtraction
C. Remove else if and use only if and else
D. Change right initialization to arr.len() - 1
Solution
Step 1: Analyze right boundary initialization
Right is set to arr.len(), which is out of bounds since indexing is 0-based.
Step 2: Fix right to arr.len() - 1 to avoid out-of-bounds access
Setting right to arr.len() - 1 ensures mid index stays within valid range.
Final Answer:
Change right initialization to arr.len() - 1 -> Option D
Quick Check:
Right boundary must be last valid index [OK]
Hint: Right index = length - 1 for zero-based arrays [OK]
Common Mistakes:
Using arr.len() as right causes panic
Changing while condition incorrectly
Incorrect mid calculation causing overflow
5. Given a sorted array with possible duplicate values, how can you modify binary search to find the first occurrence of a target value?
hard
A. After finding target at mid, continue searching left half to find earlier occurrence
B. Return immediately when target is found at mid
C. Search right half only after finding target
D. Use linear search after binary search to find first occurrence
Solution
Step 1: Understand duplicates and first occurrence requirement
Binary search normally returns any matching index, but to find first occurrence, we must check if earlier duplicates exist.
Step 2: Modify search to continue left after finding target
When target is found at mid, record index and continue searching left half to find if an earlier occurrence exists.
Final Answer:
After finding target at mid, continue searching left half to find earlier occurrence -> Option A
Quick Check:
Find first occurrence by searching left after match [OK]
Hint: Keep searching left half after finding target [OK]
Common Mistakes:
Stopping search immediately on first match
Searching right half instead of left
Using linear search unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.