0
0
Rubyprogramming~5 mins

Comparison operators in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Comparison operators
O(n)
Understanding Time Complexity

When we use comparison operators, the computer checks values to decide something.

We want to see how the time to do these checks grows as we compare more items.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def count_greater_than(numbers, threshold)
  count = 0
  numbers.each do |num|
    count += 1 if num > threshold
  end
  count
end

This code counts how many numbers in a list are bigger than a given threshold.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Comparing each number to the threshold using > operator.
  • How many times: Once for every number in the list.
How Execution Grows With Input

Explain the growth pattern intuitively.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the list gets bigger.

Common Mistake

[X] Wrong: "Comparison operators take the same time no matter how many items we check."

[OK] Correct: Each comparison happens for every item, so more items mean more comparisons and more time.

Interview Connect

Understanding how comparisons add up helps you explain how your code handles bigger data smoothly.

Self-Check

"What if we changed the code to stop checking as soon as we find one number greater than the threshold? How would the time complexity change?"