0
0
R Programmingprogramming~5 mins

Function definition in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function definition
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

The function does the same small task no matter what number you give it.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The work stays the same no matter how big the input number is.

Final Time Complexity

Time Complexity: O(1)

This means the function takes the same short time to run no matter the input size.

Common Mistake

[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.

Interview Connect

Understanding how simple functions behave helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if the function used a loop to add 1 multiple times based on the input? How would the time complexity change?"