0
0
R Programmingprogramming~5 mins

Code chunks and output in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Code chunks and output
O(n)
Understanding Time Complexity

We want to see how the time to run code chunks grows as we add more lines or commands.

How does the number of code chunks affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# Print numbers from 1 to n
print_numbers <- function(n) {
  for (i in 1:n) {
    print(i)
  }
}

print_numbers(5)
    

This code prints numbers from 1 up to n, one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints each number.
  • How many times: Exactly n times, once for each number.
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 with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items printed.

Common Mistake

[X] Wrong: "The code runs instantly no matter how big n is."

[OK] Correct: Each number must be printed one by one, so more numbers mean more time.

Interview Connect

Understanding how loops affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we changed the loop to print only every second number? How would the time complexity change?"