0
0
R Programmingprogramming~5 mins

If-else statements in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else statements
O(1)
Understanding Time Complexity

We want to see how the time it takes to run if-else statements changes as the input changes.

Are these statements quick no matter what, or do they take longer with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


value <- 7
if (value > 10) {
  print("Greater than 10")
} else if (value > 5) {
  print("Between 6 and 10")
} else {
  print("5 or less")
}
    

This code checks a number and prints a message depending on its size.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single if-else checks (no loops or repeated steps)
  • How many times: Exactly once per run
How Execution Grows With Input

Checking conditions happens once, no matter the input size.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

Pattern observation: The number of checks stays the same even if the input number grows.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if-else does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "If-else statements take longer when the input number is bigger."

[OK] Correct: The checks happen once and do not repeat, so the size of the number does not affect how long the code runs.

Interview Connect

Understanding that simple if-else checks run quickly no matter the input helps you explain how your code handles decisions efficiently.

Self-Check

"What if we added a loop that runs the if-else check for each item in a list? How would the time complexity change?"