Ternary operator in C++ - Time & Space Complexity
We want to see how the time to run code with a ternary operator changes as input grows.
Does using a ternary operator affect how long the program takes?
Analyze the time complexity of the following code snippet.
int max = (a > b) ? a : b;
return max;
This code picks the bigger of two numbers using the ternary operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison between two values.
- How many times: Exactly once, no loops or repeats.
The code always does one comparison no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same even if input grows.
Time Complexity: O(1)
This means the time to run does not change with input size; it stays constant.
[X] Wrong: "The ternary operator makes the code slower because it looks like an if-else inside a single line."
[OK] Correct: The ternary operator is just a shortcut for a simple check and runs in constant time, just like an if-else.
Understanding that simple operations like the ternary operator run in constant time helps you explain code efficiency clearly and confidently.
"What if we used the ternary operator inside a loop that runs n times? How would the time complexity change?"