📖 Scenario: You have a sorted list of book titles in a library catalog. You want to find if a specific book is available quickly without checking every title one by one.
🎯 Goal: Build a Rust program that uses binary search to find a book title in a sorted list by dividing the search space in half repeatedly.
📋 What You'll Learn
Create a sorted vector of book titles called books with these exact values: "Algorithms", "Data Structures", "Networking", "Operating Systems", "Rust Programming"
Create a variable called target and set it to the book title "Networking"
Write a function called binary_search that takes a slice of strings and a target string, and returns an Option<usize> with the index of the target or None if not found
Use divide and conquer by checking the middle element and recursively searching the left or right half
Print the result index or None if the book is not found
💡 Why This Matters
🌍 Real World
Binary search is used in many software systems to quickly find data in sorted lists, such as searching in databases, dictionaries, or indexes.
💼 Career
Understanding binary search helps in optimizing search operations and is a common interview question for software engineering roles.
Progress0 / 4 steps
1
Create the sorted list of book titles
Create a vector called books with these exact strings in order: "Algorithms", "Data Structures", "Networking", "Operating Systems", "Rust Programming"
DSA Rust
Hint
Use vec![...] to create a vector with the exact book titles in order.
2
Set the target book title
Create a variable called target and set it to the string "Networking"
DSA Rust
Hint
Use let target = "Networking"; to create the target variable.
3
Write the binary search function
Write a function called binary_search that takes slice: &[&str] and target: &str and returns Option<usize>. Use divide and conquer by checking the middle element and recursively searching the left or right half.
DSA Rust
Hint
Use recursion and compare the middle element with the target. Return the index if found, else search left or right half.
4
Print the search result
Call binary_search with books.as_slice() and target, then print the result using println!
DSA Rust
Hint
Use println!("{:?}", result); to print the Option result.
Practice
(1/5)
1. What is the main idea behind Binary Search as a divide and conquer algorithm?
easy
A. Sort the list first, then search linearly
B. Check every element one by one until the target is found
C. Repeatedly split the sorted list in half to find the target
D. Use a hash table to find the target instantly
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 C
Quick Check:
Divide and conquer = split list halves [OK]
Hint: Binary search halves the list each step [OK]
Common Mistakes:
Thinking binary search checks every element
Assuming list must be unsorted
Confusing binary search with linear search
2. Which of the following is the correct Rust function signature for a binary search function that returns an Option<usize>?
easy
A. fn binary_search(arr: &[i32], target: i32) -> Option<usize>
B. fn binary_search(arr: Vec bool
C. fn binary_search(arr: &[i32], target: i32) -> usize
D. fn binary_search(arr: &mut [i32], target: i32) -> i32
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 A
Quick Check:
Return Option<usize> for index or None [OK]
Hint: Use Option<usize> to handle found or not found [OK]
Common Mistakes:
Returning usize without Option causes errors if not found
Using Vec instead of slice for input unnecessarily
Returning bool loses index information
3. What will be the output of this Rust code snippet using binary search?
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));
}
medium
A. Some(3)
B. Some(2)
C. None
D. Some(1)
Solution
Step 1: Trace binary search on array [2,4,6,8,10] for target 6
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.