Comparison operators in Ruby - Time & Space 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.
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 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.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The number of comparisons grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[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.
Understanding how comparisons add up helps you explain how your code handles bigger data smoothly.
"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?"