0
0
Pythonprogramming~5 mins

Writing multiple lines in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing multiple lines
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 20 print actions
100About 200 print actions
1000About 2000 print actions

Pattern observation: The total work grows roughly twice as fast as n because there are two loops each doing n steps.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how multiple steps add up helps you explain your code clearly and shows you know how programs grow with input size.

Self-Check

"What if the two loops were nested inside each other? How would the time complexity change?"