If-else statements in R Programming - Time & Space 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?
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 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
Checking conditions happens once, no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks |
| 100 | 3 checks |
| 1000 | 3 checks |
Pattern observation: The number of checks stays the same even if the input number grows.
Time Complexity: O(1)
This means the time to run the if-else does not grow with input size; it stays constant.
[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.
Understanding that simple if-else checks run quickly no matter the input helps you explain how your code handles decisions efficiently.
"What if we added a loop that runs the if-else check for each item in a list? How would the time complexity change?"