0
0
R Programmingprogramming~5 mins

Numeric type in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Numeric type
O(n)
Understanding Time Complexity

We want to understand how the time to work with numeric types changes as the size of the numbers or data grows.

How does the time needed to perform numeric operations grow when we handle bigger or more numbers?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# Sum numbers from 1 to n
sum_numbers <- function(n) {
  total <- 0
  for (i in 1:n) {
    total <- total + i
  }
  return(total)
}

result <- sum_numbers(1000)
print(result)
    

This code adds all numbers from 1 up to n and returns the total sum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding a number to the total inside a loop.
  • How many times: The loop runs n times, once for each number from 1 to n.
How Execution Grows With Input

As n grows, the number of additions grows the same way.

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

Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the sum grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Adding numbers from 1 to n takes the same time no matter how big n is."

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

Interview Connect

Understanding how loops over numbers affect time helps you explain and improve code that processes data step by step.

Self-Check

"What if we used a built-in function that sums numbers without a loop? How would the time complexity change?"