0
0
Rubyprogramming~5 mins

Boolean values (true, false, nil) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Boolean values (true, false, nil)
O(n)
Understanding Time Complexity

When working with Boolean values like true, false, and nil in Ruby, it is helpful to understand how fast these checks run.

We want to know how the time to check these values changes as the program runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


values = [true, false, nil, true, false]
values.each do |val|
  if val == true
    puts "It's true!"
  elsif val == false
    puts "It's false!"
  else
    puts "It's nil or something else"
  end
end
    

This code checks each value in a list to see if it is true, false, or nil and prints a message.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the array.
  • How many times: Once for each element in the array.
How Execution Grows With Input

As the number of values grows, the program checks each one once.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the list gets longer.

Common Mistake

[X] Wrong: "Checking true, false, or nil is slow because it involves many conditions."

[OK] Correct: Each check is simple and fast; the main time cost comes from how many items you check, not the conditions themselves.

Interview Connect

Understanding how simple checks scale helps you explain your code's speed clearly and confidently in real situations.

Self-Check

"What if we changed the array to a nested array and checked values inside each sub-array? How would the time complexity change?"