0
0
R Programmingprogramming~5 mins

Variable scope (lexical scoping) in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variable scope (lexical scoping)
O(n)
Understanding Time Complexity

We want to see how the time to run code changes when using variables inside and outside functions.

How does the place where a variable is defined affect how long the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


outer_function <- function(n) {
  x <- 0
  inner_function <- function() {
    for (i in 1:n) {
      x <<- x + i
    }
    return(x)
  }
  inner_function()
}
outer_function(1000)
    

This code defines a function inside another function and uses a variable from the outer function inside a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside inner_function that runs from 1 to n.
  • How many times: It runs exactly n times, where n is the input size.
How Execution Grows With Input

Each time n gets bigger, the loop runs more times, so the work grows in a straight line with n.

Input Size (n)Approx. Operations
1010 loop steps
100100 loop steps
10001000 loop steps

Pattern observation: The number of steps grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as the input number n grows.

Common Mistake

[X] Wrong: "Using a variable from outside the inner function makes the code slower or more complex."

[OK] Correct: The variable access is quick because R uses lexical scoping, so it finds the variable without extra loops or work.

Interview Connect

Understanding how variable scope affects performance helps you write clear and efficient code, a skill valued in many programming tasks.

Self-Check

"What if the inner function created its own local variable instead of using the outer one? How would the time complexity change?"