If, elsif, else statements in Ruby - Time & Space Complexity
We want to understand how the time it takes to run if, elsif, else statements changes as the input changes.
Specifically, we ask: does adding more conditions make the program slower?
Analyze the time complexity of the following code snippet.
def check_number(num)
if num < 0
"Negative"
elsif num == 0
"Zero"
else
"Positive"
end
end
This code checks if a number is negative, zero, or positive and returns a string accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking conditions one by one.
- How many times: At most, it checks each condition once in order until one matches.
Each time the function runs, it checks conditions in order. The number of checks does not grow with input size but depends on how many conditions there are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 checks max |
| 100 | 3 checks max |
| 1000 | 3 checks max |
Pattern observation: The number of checks stays the same no matter how big the input number is.
Time Complexity: O(1)
This means the time to run the if, elsif, else statements stays constant no matter the input size.
[X] Wrong: "More input means more time because the code checks all conditions every time."
[OK] Correct: The code stops checking as soon as one condition matches, and the number of conditions is fixed, so input size does not affect time.
Understanding that simple condition checks run in constant time helps you explain how your code behaves efficiently, which is a useful skill in many programming tasks.
"What if we added a loop inside each condition that runs n times? How would the time complexity change?"