0
0
R Programmingprogramming~5 mins

Running R code in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Running R code
O(n)
Understanding Time Complexity

When we run R code, we want to know how long it takes as the input grows.

We ask: How does the work increase when we run more or bigger data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

run_r_code <- function(n) {
  result <- numeric(n)
  for (i in 1:n) {
    result[i] <- i * 2
  }
  return(result)
}

This code runs a loop from 1 to n and doubles each number, storing it in a result vector.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs from 1 to n.
  • How many times: Exactly n times, once for each number.
How Execution Grows With Input

As n grows, the loop runs more times, so the work grows directly with n.

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

Pattern observation: Doubling the input doubles the work needed.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The loop runs faster because doubling a number is simple."

[OK] Correct: Even if the operation is simple, the loop still runs n times, so time grows with n.

Interview Connect

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

Self-Check

"What if we replaced the for-loop with a vectorized operation? How would the time complexity change?"