0
0
Rubyprogramming~5 mins

If, elsif, else statements in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If, elsif, else statements
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run if, elsif, else statements changes as the input changes.

Specifically, we ask: does adding more conditions make the program slower?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def check_number(num)
  if num < 0
    "Negative"
  elsif num == 0
    "Zero"
  else
    "Positive"
  end
end

This code checks if a number is negative, zero, or positive and returns a string accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking conditions one by one.
  • How many times: At most, it checks each condition once in order until one matches.
How Execution Grows With Input

Each time the function runs, it checks conditions in order. The number of checks does not grow with input size but depends on how many conditions there are.

Input Size (n)Approx. Operations
103 checks max
1003 checks max
10003 checks max

Pattern observation: The number of checks stays the same no matter how big the input number is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if, elsif, else statements stays constant no matter the input size.

Common Mistake

[X] Wrong: "More input means more time because the code checks all conditions every time."

[OK] Correct: The code stops checking as soon as one condition matches, and the number of conditions is fixed, so input size does not affect time.

Interview Connect

Understanding that simple condition checks run in constant time helps you explain how your code behaves efficiently, which is a useful skill in many programming tasks.

Self-Check

"What if we added a loop inside each condition that runs n times? How would the time complexity change?"