For-in loop with ranges in Swift - Time & Space Complexity
When we use a for-in loop with ranges in Swift, we want to know how the time it takes to run changes as the range gets bigger.
We ask: How does the number of steps grow when the range increases?
Analyze the time complexity of the following code snippet.
for i in 1...n {
print(i)
}
This code prints numbers from 1 up to n using a for-in loop with a range.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs once for each number from 1 to n.
- How many times: Exactly n times, where n is the size of the range.
As n gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of steps grows directly with n; if n doubles, steps double too.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the range.
[X] Wrong: "The loop runs in constant time because it just prints numbers."
[OK] Correct: Even though printing is simple, the loop runs once for each number, so time grows with n.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs scale.
"What if we changed the range to stride(from: 1, through: n, by: 2)? How would the time complexity change?"