Default argument values in R Programming - Time & Space 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?
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 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.
Each time we increase x, the loop runs more times, doing more additions.
| Input Size (x) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with x. Double x, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size x.
[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.
Understanding how default arguments affect performance helps you explain your code clearly and shows you know what really matters for speed.
"What if the default argument was a function call that runs a loop itself? How would the time complexity change?"