Function definition in R Programming - Time & Space Complexity
When we define a function, we want to know how long it takes to run when we use it with different inputs.
We ask: How does the time to run change as the input size grows?
Analyze the time complexity of the following code snippet.
my_function <- function(x) {
result <- x + 1
return(result)
}
output <- my_function(5)
print(output)
This code defines a simple function that adds 1 to a number and returns the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single addition operation inside the function.
- How many times: Exactly once each time the function is called.
The function does the same small task no matter what number you give it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work stays the same no matter how big the input number is.
Time Complexity: O(1)
This means the function takes the same short time to run no matter the input size.
[X] Wrong: "The function takes longer if the input number is bigger because the number is bigger."
[OK] Correct: The function just adds 1 once, so the size of the number does not change how long it takes.
Understanding how simple functions behave helps you explain your code clearly and shows you know how to think about efficiency.
"What if the function used a loop to add 1 multiple times based on the input? How would the time complexity change?"