0
0
R Programmingprogramming~5 mins

For loop in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of print operations grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly in proportion to n. Double n, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the loop grows in a straight line with the number of times it runs.

Common Mistake

[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.

Interview Connect

Understanding how loops grow with input size helps you explain your code's efficiency clearly and confidently in real situations.

Self-Check

"What if we added a nested for loop inside this loop? How would the time complexity change?"