For loop (rarely used in Ruby) - Time & Space Complexity
We want to understand how the time it takes to run a for loop in Ruby changes as the amount of data grows.
How does the number of steps grow when the loop runs over more items?
Analyze the time complexity of the following code snippet.
for i in 1..n
puts i
end
This code prints numbers from 1 up to n using a for loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop runs the print command once for each number.
- How many times: Exactly n times, where n is the size of the range.
As n grows, the number of print steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The steps increase evenly as n increases.
Time Complexity: O(n)
This means the time grows directly in proportion to the number of items we loop over.
[X] Wrong: "The for loop runs in constant time no matter how big n is."
[OK] Correct: Because the loop runs once for each number, more numbers mean more steps, so time grows with n.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we replaced the for loop with a nested for loop inside it? How would the time complexity change?"