For-in with where clause in Swift - Time & Space Complexity
We want to understand how the time it takes to run a loop with a condition changes as the input grows.
How does adding a filter inside a loop affect the total work done?
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers where number % 2 == 0 {
print(number)
}
This code loops through a list of numbers and prints only the even ones.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for every item in the list, regardless of the condition.
As the list gets bigger, the loop checks each item once, even if it only prints some.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the size of the list.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Because we only print some items, the loop runs fewer times."
[OK] Correct: The loop still checks every item to decide if it should print, so it runs once per item.
Understanding how conditions inside loops affect performance helps you write efficient code and explain your reasoning clearly.
"What if we replaced the 'where' clause with an 'if' statement inside the loop? How would the time complexity change?"