Linear Search Algorithm in DSA Rust - Time & Space Complexity
We want to understand how the time taken by linear search changes as the list size grows.
Specifically, how many steps does it take to find an item or decide it's not there?
Analyze the time complexity of the following code snippet.
fn linear_search(arr: &[i32], target: i32) -> Option {
for (index, &value) in arr.iter().enumerate() {
if value == target {
return Some(index);
}
}
None
}
This code looks through each item in the list one by one to find the target value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each element in the array one by one.
- How many times: Up to n times, where n is the number of elements in the array.
As the list gets bigger, the number of checks grows roughly the same as the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of steps grows directly with the size of the list.
Time Complexity: O(n)
This means the time to find the target grows linearly with the number of elements.
[X] Wrong: "Linear search always takes the same time no matter the list size."
[OK] Correct: The search time depends on where the target is or if it is missing, so bigger lists usually take more time.
Understanding linear search time helps you compare it with faster methods like binary search and shows you how to reason about simple algorithms.
"What if the array was sorted and we used binary search instead? How would the time complexity change?"
Practice
Linear Search Algorithm?Solution
Step 1: Understand linear search process
Linear search checks each element in order from start to end.Step 2: Compare with other search methods
Binary search divides list, hash uses extra memory, linear is simple sequential check.Final Answer:
Check each element one by one until the target is found or list ends -> Option DQuick Check:
Linear search = sequential check [OK]
- Confusing linear search with binary search
- Thinking linear search requires sorted data
- Assuming linear search uses extra memory
arr?Solution
Step 1: Identify correct Rust for loop syntax
Rust usesfor i in 0..arr.len()to loop over indices.Step 2: Check other options for syntax errors
for i in arriterates over values, not indices;whileneeds initialization;loop i inis invalid.Final Answer:
for i in 0..arr.len() { } -> Option CQuick Check:
Rust for loop over range = for i in 0..len() [OK]
- Using for i in arr to get indices instead of values
- Writing invalid loop syntax like loop i in ...
- Forgetting to initialize loop variable in while loops
let arr = vec![3, 5, 7, 9];
let target = 7;
let mut index = -1;
for i in 0..arr.len() {
if arr[i] == target {
index = i as i32;
break;
}
}
println!("{}", index);Solution
Step 1: Trace the loop to find target index
Loop checks arr[0]=3, arr[1]=5, arr[2]=7 matches target, sets index=2 and breaks.Step 2: Print the index value
After break, index is 2, so printed output is 2.Final Answer:
2 -> Option BQuick Check:
Target 7 found at index 2 [OK]
- Not breaking loop after finding target
- Printing index before loop ends
- Confusing index type casting
let arr = vec![1, 2, 3];
let target = 4;
let mut found = false;
for i in 0..arr.len() {
if arr[i] = target {
found = true;
break;
}
}
println!("{}", found);Solution
Step 1: Check the if condition syntax
The code uses '=' which is assignment, not comparison. It should be '==' to compare values.Step 2: Verify other options
Changing 'found' type or removing break won't fix syntax error. Using while loop is valid but not necessary.Final Answer:
Use '==' for comparison instead of '=' -> Option AQuick Check:
Comparison needs '==' not '=' [OK]
- Using '=' instead of '==' in if conditions
- Removing break causing unnecessary iterations
- Changing variable types unnecessarily
arr using linear search in Rust. Which approach correctly collects all matching indices?Solution
Step 1: Understand requirement to find all indices
We must check every element and collect indices where element equals target.Step 2: Evaluate options for correctness
Breaking loop stops early, sorting changes order, hash map counts but doesn't store indices. Only pushing indices in loop works.Final Answer:
Use a loop over indices, push index to a vector when element equals target -> Option AQuick Check:
Collect all matches by looping and storing indices [OK]
- Breaking loop too early to find all matches
- Sorting vector which changes original order
- Using hash map counts instead of indices
Ready to prove it?
Pass the test and this pattern moves unknown
