What if you could find any name in a huge book in just a few quick steps?
Why Binary Search as Divide and Conquer in DSA Rust?
Imagine you have a huge phone book with thousands of names sorted alphabetically. You want to find one name, but you start from the first page and check every name one by one.
This manual way is very slow and tiring. It takes a long time to find the name because you look at every single entry. If the book is very big, you might get frustrated or make mistakes.
Binary Search uses a smart trick: it looks at the middle of the book first. If the name you want is before the middle, it ignores the second half. If it is after, it ignores the first half. It keeps cutting the search area in half until it finds the name quickly.
fn find_name(names: &[&str], target: &str) -> Option<usize> {
for i in 0..names.len() {
if names[i] == target {
return Some(i);
}
}
None
}fn binary_search(names: &[&str], target: &str) -> Option<usize> {
let mut left = 0;
let mut right = names.len();
while left < right {
let mid = left + (right - left) / 2;
if names[mid] == target {
return Some(mid);
} else if names[mid] < target {
left = mid + 1;
} else {
right = mid;
}
}
None
}This method makes searching in large sorted lists super fast and efficient, saving time and effort.
When you search for a contact on your phone, the phone uses a method like binary search to find the name quickly instead of scrolling through the entire list.
Manual search checks every item one by one, which is slow.
Binary Search divides the list and ignores half each time, speeding up search.
It works only on sorted lists and is very efficient for large data.
Practice
Binary Search as a divide and conquer algorithm?Solution
Step 1: Understand divide and conquer in binary search
Binary search works by dividing the sorted list into two halves and deciding which half to search next.Step 2: Identify the correct approach
It repeatedly splits the list in half, narrowing down the search space until the target is found or no elements remain.Final Answer:
Repeatedly split the sorted list in half to find the target -> Option CQuick Check:
Divide and conquer = split list halves [OK]
- Thinking binary search checks every element
- Assuming list must be unsorted
- Confusing binary search with linear search
Option<usize>?Solution
Step 1: Understand Rust function signature for binary search
The function takes a slice of integers and a target integer, returning an Option with the index if found.Step 2: Match the correct signature
Option<usize> is used to return Some(index) if found or None if not found, matching fn binary_search(arr: &[i32], target: i32) -> Option<usize>.Final Answer:
fn binary_search(arr: &[i32], target: i32) -> Option<usize> -> Option AQuick Check:
Return Option<usize> for index or None [OK]
- Returning usize without Option causes errors if not found
- Using Vec instead of slice for input unnecessarily
- Returning bool loses index information
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut left = 0;
let mut right = arr.len() - 1;
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
}
fn main() {
let nums = [2, 4, 6, 8, 10];
println!("{:?}", binary_search(&nums, 6));
}Solution
Step 1: Trace binary search on array [2,4,6,8,10] for target 6
Initial left=0, right=4, mid=2. arr[2]=6 matches target.Step 2: Return index 2 wrapped in Some
Since arr[mid] == target, function returns Some(2).Final Answer:
Some(2) -> Option BQuick Check:
Index of 6 in array is 2 [OK]
- Off-by-one errors in mid calculation
- Confusing index with value
- Returning None incorrectly when target exists
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
}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 DQuick Check:
Right boundary must be last valid index [OK]
- Using arr.len() as right causes panic
- Changing while condition incorrectly
- Incorrect mid calculation causing overflow
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 AQuick Check:
Find first occurrence by searching left after match [OK]
- Stopping search immediately on first match
- Searching right half instead of left
- Using linear search unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
