O(n²) and Nested Loops
Big-O: lesson 3 of 5
Every pair costs you. Nested loops explode fast.
Lesson 3 of 5 · 5 min
O(n²) and Nested Loops
Step 1 of 17
- comparisons
- 0 / 15
- n²
- 36 squares
- i · j
- —
Every square is one possible pair. A nested loop is a machine for visiting them.
The Idea
When a loop runs inside another loop over the same data, you do n units of work n times. That is O(n²). It feels perfectly fine on ten items and freezes solid on ten thousand.
Real-World Example
Picture a party where every guest greets every other guest. Ten guests produce 45 handshakes; a hundred guests produce 4,950. The room grew ten times, but the greeting count grew a hundred times.
The Code
def has_duplicate(nums):
n = len(nums)
# outer loop picks each item...
for i in range(n):
# ...inner loop compares it against the rest
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return False
# roughly n*n/2 comparisons -> O(n^2)
Your turn
Fill in the blank.
count = 0
for i in range(4):
for j in range(4):
count += 1
# count is now ___Mini quiz
1 / 3