Guard for early exit pattern in Swift - Time & Space Complexity
We want to see how using a guard statement to exit early affects how long the code runs.
Does this pattern change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
func findFirstPositive(_ numbers: [Int]) -> Int? {
for number in numbers {
guard number > 0 else { continue }
return number
}
return nil
}
This code looks for the first positive number in a list and stops as soon as it finds one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to all elements, but usually stops early when a positive number is found.
As the list gets bigger, the code might check more numbers, but it can stop early if it finds a positive number quickly.
| 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 number of checks grows with input size but can stop early, so actual work varies.
Time Complexity: O(n)
This means in the worst case, the code looks at every item once, but it can finish sooner if it finds what it needs early.
[X] Wrong: "Using guard for early exit always makes the code run faster for all inputs."
[OK] Correct: Sometimes the positive number is near the end or missing, so the code still checks many items, making the time grow with input size.
Understanding how early exit patterns affect time helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if we changed the guard to check for a different condition that rarely happens? How would the time complexity change?"