Nested while loops in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use nested while loops, the program runs some steps inside other steps repeatedly.
We want to know how the total work grows as the input gets bigger.
Analyze the time complexity of the following code snippet.
i = 0
while i < n:
j = 0
while j < n:
print(i, j)
j += 1
i += 1
This code prints pairs of numbers from 0 up to n-1 using two loops inside each other.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner while loop that prints pairs.
- How many times: The inner loop runs n times for each of the n times the outer loop runs.
As n grows, the total prints grow much faster because each outer step triggers many inner steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 |
| 100 | 10,000 |
| 1000 | 1,000,000 |
Pattern observation: The work grows by the square of n, so doubling n makes the work about four times bigger.
Time Complexity: O(n²)
This means if the input doubles, the total steps roughly become four times more.
[X] Wrong: "The nested loops just add their times, so it is O(n + n) = O(n)."
[OK] Correct: The inner loop runs completely for each outer loop step, so the total work multiplies, not adds.
Understanding nested loops helps you explain how programs handle repeated tasks inside other repeated tasks, a common pattern in coding challenges.
"What if the inner loop ran only up to a fixed number instead of n? How would the time complexity change?"
Practice
while condition1:
while condition2:
# codeSolution
Step 1: Understand nested loops structure
The outer loop runs while condition1 is true. For each iteration of this outer loop, the inner loop runs fully while condition2 is true.Step 2: Explain the inner loop behavior
The inner loop completes all its iterations before the outer loop moves to the next iteration.Final Answer:
Runs the inner loop completely for each iteration of the outer loop -> Option AQuick Check:
Inner loop runs fully inside outer loop [OK]
- Thinking both loops run only once
- Confusing order of loop execution
- Assuming inner loop runs only if outer loop is false
Solution
Step 1: Check indentation and colons
Python requires a colon after while conditions and proper indentation for nested blocks.Step 2: Identify correct indentation and syntax
while x < 3: while y < 2: print(x, y) y += 1 uses colons and indents the inner while and print statements correctly.Final Answer:
while x < 3: while y < 2: print(x, y) y += 1 -> Option DQuick Check:
Correct colons and indentation = while x < 3: while y < 2: print(x, y) y += 1 [OK]
- Missing colons after while statements
- Incorrect indentation of inner loop
- Mixing indentation levels
i = 1
while i <= 2:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1Solution
Step 1: Trace outer loop iterations
i starts at 1 and runs while i <= 2, so i = 1 and i = 2.Step 2: Trace inner loop iterations for each i
For each i, j runs from 1 to 3, printing i and j each time.Final Answer:
1 1\n1 2\n1 3\n2 1\n2 2\n2 3 -> Option CQuick Check:
Inner loop prints 3 times per outer loop iteration [OK]
- Only printing inner loop once
- Mixing up i and j values
- Stopping loops too early
i = 0
while i < 2:
j = 0
while j < 2:
print(i, j)
j += 1
i += 1Solution
Step 1: Check indentation inside inner while loop
The print and j increment lines must be indented inside the inner while loop to run repeatedly.Step 2: Identify effect of wrong indentation
Without indentation, print and j += 1 run only once, causing an infinite loop or logic error.Final Answer:
Inner loop print and increments are not indented properly -> Option BQuick Check:
Indent inner loop body correctly [OK]
- Forgetting to indent inner loop code
- Incrementing outer loop variable inside inner loop
- Misplacing loop conditions
Solution
Step 1: Check loop ranges for 1 to 3
We want rows and columns from 1 to 3 inclusive, so conditions should be <= 3 starting at 1.Step 2: Verify sum calculation and printing format
row = 1 while row <= 3: col = 1 while col <= 3: print(row + col, end=' ') col += 1 print() row += 1 sums row and col indexes and prints with space, then prints a newline after each row.Final Answer:
row = 1 while row <= 3: col = 1 while col <= 3: print(row + col, end=' ') col += 1 print() row += 1 -> Option AQuick Check:
Correct ranges and sum print = row = 1 while row <= 3: col = 1 while col <= 3: print(row + col, end=' ') col += 1 print() row += 1 [OK]
- Starting loops at 0 instead of 1
- Using < 3 instead of <= 3 to miss last row/column
- Printing product instead of sum
