0
0
Rubyprogramming~5 mins

Case/when statement in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Case/when statement
O(n)
Understanding Time Complexity

We want to understand how long a case/when statement takes to run as the input changes.

Specifically, how does the number of checks grow when we have more conditions?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


case value
when 1
  puts "One"
when 2
  puts "Two"
when 3
  puts "Three"
else
  puts "Other"
end
    

This code checks the value against several conditions and prints a message for the first match.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each condition one by one until a match is found.
  • How many times: Up to the number of conditions (here 3), but stops early if matched.
How Execution Grows With Input

As the number of conditions grows, the checks increase roughly one by one.

Input Size (n)Approx. Operations
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of conditions.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a match grows linearly with the number of conditions.

Common Mistake

[X] Wrong: "The case statement always runs in constant time no matter how many conditions there are."

[OK] Correct: The case statement checks conditions one by one, so more conditions mean more checks and longer time.

Interview Connect

Understanding how case/when scales helps you explain how your code behaves with many conditions, a useful skill in real projects.

Self-Check

"What if we replaced the case/when with a hash lookup? How would the time complexity change?"