0
0
R Programmingprogramming~5 mins

First R program in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: First R program
O(n)
Understanding Time Complexity

We want to see how the time it takes to run a simple R program changes as we give it more work.

How does the program's running time grow when the input size grows?

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: It runs exactly n times, once for each number.
How Execution Grows With Input

As n gets bigger, the program prints more numbers, so it takes more time.

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

Pattern observation: The time grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the program grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The program 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 running time is a key skill that helps you write efficient code and explain your thinking clearly.

Self-Check

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