Upto and downto methods in Ruby - Time & Space Complexity
We want to understand how the time taken by Ruby's upto and downto methods changes as the numbers they count through get bigger.
How does the number of steps grow when counting up or down over a range?
Analyze the time complexity of the following code snippet.
start = 1
end_num = 5
start.upto(end_num) do |i|
puts i
end
end_num.downto(start) do |i|
puts i
end
This code counts up from 1 to 5 and then counts down from 5 to 1, printing each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The block inside
uptoanddowntoruns once for each number in the range. - How many times: It runs as many times as the difference between start and end numbers plus one.
As the range between start and end grows, the number of times the block runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The number of operations grows directly with the size of the range; doubling the range doubles the work.
Time Complexity: O(n)
This means the time taken grows in a straight line with the size of the range you count through.
[X] Wrong: "The upto and downto methods run in constant time no matter the range size."
[OK] Correct: Each method runs the block once for every number in the range, so the time grows as the range gets bigger.
Understanding how loops like upto and downto scale helps you explain how your code behaves with bigger inputs, a skill that shows you think about efficiency.
"What if we replaced upto with a method that skips every other number? How would the time complexity change?"