0
0
Rubyprogramming~5 mins

Ternary operator usage in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Ternary operator usage
O(1)
Understanding Time Complexity

We want to see how using the ternary operator affects how long the code 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(num)
  result = num > 0 ? "Positive" : "Non-positive"
  result
end

check_number(5)
check_number(-3)

This code uses a ternary operator to decide if a number is positive or not.

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: Runs once per function call, no loops or recursion inside.
How Execution Grows With Input

Each time we call the function, it does one quick check, no matter the number size.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations remains constant (1 check) regardless of the input size.

Final Time Complexity

Time Complexity: O(1)

This means the operation takes the same small amount of time no matter what number you check.

Common Mistake

[X] Wrong: "The ternary operator makes the code slower because it looks complicated."

[OK] Correct: The ternary operator is just a short way to write an if-else check. It runs just as fast as a simple if-else statement.

Interview Connect

Understanding how simple operations like the ternary operator work helps you explain your code clearly and shows you know how code speed relates to what you write.

Self-Check

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