Semicolons are optional behavior in Swift - Time & Space Complexity
We want to see how using semicolons affects how long Swift code takes to run.
Does adding or skipping semicolons change the speed of the program?
Analyze the time complexity of the following code snippet.
var sum = 0
for i in 1...n {
sum += i
}
print(sum)
This code adds numbers from 1 to n and prints the total. Semicolons are not used here.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds numbers from 1 to n.
- How many times: It runs exactly n times, once for each number.
As n grows, the loop runs more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n, no matter if semicolons are used or not.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Adding semicolons makes the program run slower or faster."
[OK] Correct: Semicolons only help separate statements; they do not affect how many times the code runs or how fast it executes.
Understanding what affects time complexity helps you focus on the real parts that slow down code, not small syntax choices like semicolons.
"What if we replaced the for-loop with a recursive function? How would the time complexity change?"