Running scripts with ruby command - Time & Space Complexity
When we run Ruby scripts using the ruby command, it's helpful to know how the time it takes grows as the script processes more data.
We want to understand how the script's running time changes when the input size changes.
Analyze the time complexity of the following code snippet.
def print_numbers(n)
i = 0
while i < n
puts i
i += 1
end
end
print_numbers(5)
This code prints numbers from 0 up to n-1 using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that prints numbers.
- How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the script grows in a straight line with the input size.
[X] Wrong: "The script runs instantly no matter how big n is."
[OK] Correct: Each number must be printed one by one, so more numbers mean more time.
Understanding how loops affect running time helps you explain your code clearly and shows you can think about efficiency.
"What if we changed the loop to print only even numbers up to n? How would the time complexity change?"