0
0
R Programmingprogramming~5 mins

Function arguments in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function arguments
O(n)
Understanding Time Complexity

When we use functions with arguments, it is important to see how the time to run the function changes as the input changes.

We want to know: how does the work inside the function grow when the input size grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


my_sum <- function(x) {
  total <- 0
  for (i in seq_along(x)) {
    total <- total + x[i]
  }
  return(total)
}

values <- 1:100
my_sum(values)
    

This function adds up all numbers in a vector given as an argument.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each element of the input vector.
  • How many times: Once for each item in the input vector.
How Execution Grows With Input

As the input vector gets bigger, the function does more additions, one for each item.

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

Pattern observation: The work grows directly with the size of the input vector.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input vector gets bigger.

Common Mistake

[X] Wrong: "The function runs in the same time no matter how big the input is."

[OK] Correct: Because the function adds each number one by one, more numbers mean more work and more time.

Interview Connect

Understanding how function arguments affect time helps you explain how your code handles different input sizes clearly and confidently.

Self-Check

"What if the function used two loops, each going through the input vector? How would the time complexity change?"