Repeat-while loop in Swift - Time & Space Complexity
We want to understand how the time it takes to run a repeat-while loop changes as the input grows.
Specifically, how many times the loop runs depending on the input size.
Analyze the time complexity of the following code snippet.
var count = 0
let limit = n
repeat {
print(count)
count += 1
} while count < limit
This code prints numbers from 0 up to n-1 using a repeat-while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The repeat-while loop runs the print and increment steps.
- How many times: It runs once for each number from 0 up to n-1, so n times.
As n grows, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows in a straight line with input size.
Time Complexity: O(n)
This means the time to run the loop grows directly with the size of n.
[X] Wrong: "The repeat-while loop runs only once because it always runs at least once."
[OK] Correct: The loop runs once at minimum, but then keeps running until the condition is false, so it can run many times depending on n.
Understanding how loops grow with input size helps you explain your code clearly and shows you can think about efficiency.
"What if we changed the loop to stop when count <= limit instead of count < limit? How would the time complexity change?"