0
0
R Programmingprogramming~5 mins

Default argument values in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default argument values
O(n)
Understanding Time Complexity

We want to see how using default values for function arguments affects how long the code takes to run.

Does having default values change the work done when the function runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


my_sum <- function(x, y = 10) {
  total <- 0
  for (i in 1:x) {
    total <- total + i + y
  }
  return(total)
}

result <- my_sum(5)

This function adds numbers from 1 to x, adding y each time. If y is not given, it uses 10.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

Each time we increase x, the loop runs more times, doing more additions.

Input Size (x)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with x. Double x, double the work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using a default value makes the function faster or slower depending on the value."

[OK] Correct: The default value is just a number used inside the loop. It does not change how many times the loop runs, so it does not affect the time complexity.

Interview Connect

Understanding how default arguments affect performance helps you explain your code clearly and shows you know what really matters for speed.

Self-Check

"What if the default argument was a function call that runs a loop itself? How would the time complexity change?"