Loop with break in Rust - Time & Space Complexity
We want to understand how the time a loop takes changes when it can stop early using a break.
How does stopping early affect how long the code runs?
Analyze the time complexity of the following code snippet.
fn find_first_even(numbers: &[i32]) -> Option {
for &num in numbers {
if num % 2 == 0 {
return Some(num); // break early when even number found
}
}
None
}
This code looks through a list to find the first even number and stops as soon as it finds one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list elements one by one.
- How many times: Up to the first even number or the whole list if none found.
Execution depends on where the first even number appears.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 1 and 1000 checks |
Pattern observation: The loop may stop early, so the work can be less than the list size, but in the worst case it checks every item.
Time Complexity: O(n)
This means the time grows linearly with the size of the list in the worst case.
[X] Wrong: "Because the loop can break early, the time complexity is always constant O(1)."
[OK] Correct: Sometimes the loop must check every item if no early break happens, so the worst case still grows with input size.
Understanding how early breaks affect loops helps you explain code efficiency clearly and shows you think about best and worst cases.
"What if we changed the loop to always check every element without break? How would the time complexity change?"