Limitations and best practices in Swift - Time & Space Complexity
When we write code, it is important to know how fast it runs as the input grows.
This helps us avoid slow programs and choose better ways to solve problems.
Analyze the time complexity of this example function.
func findFirstEven(numbers: [Int]) -> Int? {
for number in numbers {
if number % 2 == 0 {
return number
}
}
return nil
}
This function looks for the first even number in a list and stops when it finds one.
Look at what repeats in the code.
- Primary operation: Looping through the list of numbers.
- How many times: Up to the length of the list, but may stop early.
The time to run depends on where the first even number is.
| 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 work grows with input size but can stop early if the answer is found.
Time Complexity: O(n)
This means the time grows roughly in proportion to the size of the input list in the worst case.
[X] Wrong: "The function always checks every number in the list."
[OK] Correct: The function stops as soon as it finds an even number, so it may check fewer items.
Understanding how loops and early exits affect time helps you explain your code clearly and choose better solutions.
"What if the function searched for all even numbers instead of stopping at the first? How would the time complexity change?"