0
0
R Programmingprogramming~5 mins

Ifelse vectorized function in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ifelse vectorized function
O(n)
Understanding Time Complexity

We want to understand how the time to run the ifelse function changes as the input grows.

Specifically, how does it handle many values quickly?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

x <- 1:1000
result <- ifelse(x %% 2 == 0, "even", "odd")

This code checks each number in x to see if it is even or odd, then labels it accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each element of the vector x once.
  • How many times: Exactly once per element, so 1000 times here.
How Execution Grows With Input

Each element is checked one time, so the work grows directly with the number of elements.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: If you double the input size, the work doubles too.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "ifelse runs in constant time no matter how big the input is."

[OK] Correct: The function must check each element to decide what to return, so more elements mean more work.

Interview Connect

Understanding how vectorized functions like ifelse scale helps you write efficient code and explain your choices clearly.

Self-Check

"What if we replaced ifelse with a loop that checks each element and appends results? How would the time complexity change?"