Ternary operator in Ruby - Time & Space Complexity
We want to see how using a ternary operator affects how long a program takes to run.
Does it change the speed depending on input size?
Analyze the time complexity of the following code snippet.
def check_number(n)
result = n > 0 ? "Positive" : "Non-positive"
result
end
check_number(5)
check_number(-3)
This code checks if a number is positive using a ternary operator and returns a string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison and assignment using the ternary operator.
- How many times: Exactly once per function call, no loops or repeated steps.
Execution time stays the same no matter the input size because it only does one check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 comparison and 1 assignment |
| 100 | 1 comparison and 1 assignment |
| 1000 | 1 comparison and 1 assignment |
Pattern observation: The number of operations does not increase as input size grows.
Time Complexity: O(1)
This means the time to run stays the same no matter how big the input is.
[X] Wrong: "Using a ternary operator makes the code slower because it looks complicated."
[OK] Correct: The ternary operator is just a shortcut for an if-else and runs in constant time, so it does not slow down the program.
Understanding that simple operations like the ternary operator run in constant time helps you explain your code clearly and shows you know how to think about efficiency.
"What if we replaced the ternary operator with a loop that checks multiple conditions? How would the time complexity change?"