0
0
C++programming~5 mins

Ternary operator in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ternary operator
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

The code always does one comparison no matter the input size.

Input Size (n)Approx. Operations
101
1001
10001

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

Final Time Complexity

Time Complexity: O(1)

This means the time to run does not change with input size; it stays constant.

Common Mistake

[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.

Interview Connect

Understanding that simple operations like the ternary operator run in constant time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we used the ternary operator inside a loop that runs n times? How would the time complexity change?"