0
0
Rubyprogramming~5 mins

Ternary operator in Ruby - Time & Space Complexity

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

Scenario Under Consideration

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

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

Execution time stays the same no matter the input size because it only does one check.

Input Size (n)Approx. Operations
101 comparison and 1 assignment
1001 comparison and 1 assignment
10001 comparison and 1 assignment

Pattern observation: The number of operations does not increase as input size grows.

Final Time Complexity

Time Complexity: O(1)

This means the time to run stays the same no matter how big the input is.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we replaced the ternary operator with a loop that checks multiple conditions? How would the time complexity change?"