0
0
R Programmingprogramming~5 mins

Integer type in R Programming - Time & Space Complexity

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

When working with integers in R, it's helpful to know how operations on them grow as numbers get bigger.

We want to see how the time to do integer operations changes with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

This code adds up all integers from 1 to n using a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding an integer to total inside the 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 additions grows the same way.

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

Pattern observation: The work grows directly with n; double n means double the additions.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum integers grows in a straight line with the number of integers.

Common Mistake

[X] Wrong: "Adding integers is always instant, so time doesn't grow with n."

[OK] Correct: Each addition takes a tiny bit of time, so more numbers mean more additions and more total time.

Interview Connect

Understanding how simple integer operations scale helps you reason about bigger problems and write efficient code.

Self-Check

"What if we used a built-in function like sum() instead of a loop? How would the time complexity change?"