Break and continue behavior in Swift - Time & Space Complexity
When we use break or continue in loops, it changes how many times the loop runs. This affects how long the code takes to finish.
We want to see how these commands change the work done as the input grows.
Analyze the time complexity of the following code snippet.
var sum = 0
for i in 1...n {
if i == 5 {
break
}
if i % 2 == 0 {
continue
}
sum += i
}
This code loops from 1 to n, but stops early if i reaches 5, and skips adding even numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running from 1 to n.
- How many times: The loop stops early at i = 5 due to break, so it runs at most 5 times.
Because the loop stops at 5, the number of steps does not grow with n after a point.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 |
| 100 | 5 |
| 1000 | 5 |
Pattern observation: The work stays the same even if n gets bigger because of the break.
Time Complexity: O(1)
This means the loop runs a fixed number of times, no matter how big the input is.
[X] Wrong: "The loop always runs n times, so time is O(n)."
[OK] Correct: Because the break stops the loop early, it only runs a few times, not all n times.
Understanding how break and continue affect loops helps you explain code efficiency clearly and shows you can think about real code behavior.
"What if we removed the break statement? How would the time complexity change?"