0
0
Rubyprogramming~5 mins

Case with ranges and patterns in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Case with ranges and patterns
O(n)
Understanding Time Complexity

We want to understand how long it takes for a Ruby case statement using ranges and patterns to run as the input changes.

Specifically, how does the time grow when checking multiple conditions with ranges?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


score = 75

case score
when 0..59
  puts "Fail"
when 60..69
  puts "Pass"
when 70..79
  puts "Good"
when 80..89
  puts "Very Good"
else
  puts "Excellent"
end
    

This code checks which range the score falls into and prints a message accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking the input against each range in the case statement.
  • How many times: Each range is checked one by one until a match is found or all are checked.
How Execution Grows With Input

As the number of ranges grows, the number of checks grows too, because each range is tested in order.

Input Size (number of ranges)Approx. Operations (checks)
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

Pattern observation: The number of checks grows directly with the number of ranges to test.

Final Time Complexity

Time Complexity: O(n)

This means the time to find the matching range grows linearly with how many ranges there are.

Common Mistake

[X] Wrong: "The case statement checks all ranges at once, so time stays the same no matter how many ranges there are."

[OK] Correct: Actually, Ruby checks each range one by one until it finds a match, so more ranges mean more checks and more time.

Interview Connect

Understanding how case statements with ranges work helps you reason about condition checks in real code, which is a useful skill for writing efficient programs.

Self-Check

"What if we changed the case statement to use a hash lookup instead of ranges? How would the time complexity change?"