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?"
Practice
break keyword do inside a loop in Rust?Solution
Step 1: Understand the role of
Thebreakin loopsbreakkeyword is used to stop the loop immediately, no matter where it is in the loop.Step 2: Compare with other loop controls
Unlikecontinuewhich skips to the next iteration,breakexits the loop completely.Final Answer:
It stops the loop immediately and exits it. -> Option BQuick Check:
break= stop loop [OK]
- Confusing break with continue
- Thinking break pauses instead of stops
- Assuming break restarts the loop
loop in Rust?Solution
Step 1: Recall Rust loop break syntax
In Rust, to exit a loop, you simply writebreak;with a semicolon.Step 2: Check other options for syntax errors
break()is invalid because break is a keyword, not a function.exit loop;andstop;are not Rust keywords.Final Answer:
break; -> Option CQuick Check:
Correct break syntax = break; [OK]
- Using break as a function call
- Writing break without semicolon
- Using non-existent keywords like exit or stop
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("{}", count);
}Solution
Step 1: Trace the loop iterations and print statements
Loop starts with count = 0. Each loop adds 1 to count. When count reaches 3, break stops the loop. The print happens only if count is not 3.Step 2: List printed values
When count=1, prints 1; count=2, prints 2; count=3 triggers break before print, so 3 is not printed.Final Answer:
1 2 -> Option AQuick Check:
Print before break stops at 3, so output is 1 2 [OK]
- Assuming break prints the last value
- Counting from 0 instead of 1
- Ignoring that break stops loop before print
let mut i = 0;
loop {
if i == 5 {
break
}
println!("{}", i);
i += 1;
}Solution
Step 1: Check syntax around break statement
In Rust, statements must end with a semicolon. The break statement here lacks a semicolon.Step 2: Verify other parts of the code
Variable i is mutable, println! is correctly used, and loop without condition is valid in Rust.Final Answer:
Missing semicolon after break -> Option AQuick Check:
break needs semicolon to avoid syntax error [OK]
- Forgetting semicolon after break
- Thinking loop needs condition
- Misreading println! syntax
loop with break to do this?Solution
Step 1: Understand the problem requirements
Sum numbers from 1 to 10, but stop if sum reaches or exceeds 20. Use loop with break.Step 2: Analyze each option for correctness
let mut sum = 0; let mut n = 1; loop { sum += n; if sum >= 20 { break; } n += 1; } println!("{}", sum); breaks after adding sum >= 20 but does not stop when n > 10, so it does not enforce the limit to 10. let mut sum = 0; for n in 1..=10 { sum += n; if sum >= 20 { break; } } println!("{}", sum); uses for loop, not loop. let mut sum = 0; let mut n = 1; while n <= 10 { sum += n; if sum >= 20 { break; } n += 1; } println!("{}", sum); uses while loop, not loop. let mut sum = 0; let mut n = 1; loop { if n > 10 { break; } sum += n; if sum >= 20 { break; } n += 1; } println!("{}", sum); correctly breaks if n > 10 or sum >= 20, stopping properly.Final Answer:
Correctly uses loop with break to stop at sum >= 20 or n > 10. -> Option DQuick Check:
let mut sum = 0; let mut n = 1; loop { if n > 10 { break; } sum += n; if sum >= 20 { break; } n += 1; } println!("{}", sum);[OK]
- Missing break for loop exit condition
- Using wrong loop type
- Not checking both sum and count limits
Ready to prove it?
Pass the test and this pattern moves unknown
