Writing multiple lines in Python - Time & Space Complexity
When writing multiple lines in a program, it is important to see how the time to run the code changes as we add more lines.
We want to know how the program's work grows when we write many lines one after another.
Analyze the time complexity of the following code snippet.
for i in range(n):
print(i)
for j in range(n):
print(j * 2)
This code prints numbers from 0 to n-1, then prints double those numbers in a second loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two separate loops that each run through n items.
- How many times: Each loop runs n times, one after the other.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 print actions |
| 100 | About 200 print actions |
| 1000 | About 2000 print actions |
Pattern observation: The total work grows roughly twice as fast as n because there are two loops each doing n steps.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input size grows, even with two loops one after another.
[X] Wrong: "Two loops mean the time complexity is squared, like O(n²)."
[OK] Correct: The loops run one after the other, not inside each other, so the total time just adds up, not multiplies.
Understanding how multiple steps add up helps you explain your code clearly and shows you know how programs grow with input size.
"What if the two loops were nested inside each other? How would the time complexity change?"