For loop in R Programming - Time & Space Complexity
We want to understand how the time it takes to run a for loop changes as we increase the number of times it runs.
Basically, how does the work grow when the loop runs more times?
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, running the loop n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the for loop.
- How many times: Exactly n times, once for each number from 1 to n.
As n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly in proportion to n. Double n, double the work.
Time Complexity: O(n)
This means the time to run the loop grows in a straight line with the number of times it runs.
[X] Wrong: "The loop runs faster because it just prints numbers quickly."
[OK] Correct: Even if printing is fast, the loop still does one print per number, so the total work grows with n.
Understanding how loops grow with input size helps you explain your code's efficiency clearly and confidently in real situations.
"What if we added a nested for loop inside this loop? How would the time complexity change?"