Swift REPL and Playgrounds - Time & Space Complexity
When using Swift REPL or Playgrounds, we often write small pieces of code to test ideas quickly.
We want to understand how the time it takes to run code grows as we try bigger inputs in these tools.
Analyze the time complexity of the following Swift code snippet run in a Playground or REPL.
var sum = 0
for i in 1...n {
sum += i
}
print(sum)
This code adds numbers from 1 to n and prints the total.
Look for loops or repeated steps in the code.
- Primary operation: The for-loop that adds each number to sum.
- How many times: It runs once for each number from 1 to n.
As n gets bigger, the loop runs more times, so the work grows with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input size increases.
[X] Wrong: "The loop runs a fixed number of times, so time is constant."
[OK] Correct: The loop depends on n, so if n grows, the loop runs more times, making the time grow too.
Understanding how loops affect time helps you explain your code clearly and shows you can think about efficiency.
"What if we replaced the for-loop with a nested loop running from 1 to n inside the first loop? How would the time complexity change?"