O(n²) quadratic time
easy 14 minO(n²) means the work grows with the square of the input, usually because a loop runs inside another loop over the same data.
Video lesson · Chapter 1 of 5
One duet for every pair
O(n²) quadratic time
1:26Reel
Read caption
Mina connects each unordered pair once and watches the introductions grow quadratically. One line for every pair.
How it works
Step through the idea, or press Play.
Pick one item. The outer loop takes each of the n items in turn
Understand it
Start here
What O(n²) means
An algorithm is O(n²), or quadratic, when its work grows with the square of the input size. It almost always comes from nested loops: for each of items, do something with each of the items. 10 items cost about 100 steps, 1,000 items about a million. It is the usual cost of the brute-force answer: it works, but it does not scale.
Loops multiply
A loop of inside a loop of runs its body times.
Double n, four times the work
. Ten times the data costs a hundred times the time.
Often escapable
A hash set, a hash map or sorting first turns many quadratic problems into or .
The core count
The pattern
The nested loop
def count_nested(n): ops = 0 for i in range(n): # n times for j in range(n): # n times for EACH i ops += 1 # the body runs n * n times return opsfor n in [4, 10, 100, 1000]: print(n, count_nested(n)) # 16, 100, 10000, 1000000How two nested loops run
The math
Counting the triangle
Most quadratic algorithms do not run the inner loop a full times. Bubble sort, selection sort and the all-pairs check all start the inner loop later each round, so the work forms a triangle: steps, then , down to 1. Add them up with the arithmetic series formula.
The sum behind every pair loop
Why that is still O(n²)
Inner loop runs for n = 7 (j from i + 1)
| Outer i | 0 | 1 | 2 | 3 | 4 | 5 | Total |
|---|---|---|---|---|---|---|---|
| Inner runs | 6 | 5 | 4 | 3 | 2 | 1 | 21 |
range(n) for both loops you would get ; starting at gives 21. Both are .Scale
The danger zone
| n | at 1 µs per step | |||
|---|---|---|---|---|
| 10 | 10 | 33 | 100 | 0.1 ms |
| 100 | 100 | 664 | 10,000 | 10 ms |
| 1,000 | 1,000 | about 10,000 | 1,000,000 | 1 second |
| 10,000 | 10,000 | about 133,000 | about 1.7 minutes | |
| 100,000 | 100,000 | about 1.7 million | about 2.8 hours | |
| 1,000,000 | 1,000,000 | about 20 million | about 11.6 days |
Scaling the input
Example 1
Bubble sort
Bubble sort compares neighbours and swaps them when the left one is bigger. One pass carries the largest unsorted value to the end, like a bubble rising. Pass 1 makes comparisons, pass 2 makes , and so on: in total. On [5, 3, 8, 1, 9, 2, 7] that is 21 comparisons and 10 swaps.
One pass of bubble sort
def bubble_sort(arr): n = len(arr) comparisons = 0 for i in range(n - 1): swapped = False for j in range(n - 1 - i): comparisons += 1 if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: # no swaps: already sorted break return arr, comparisonsprint(bubble_sort([5, 3, 8, 1, 9, 2, 7])) # ([1, 2, 3, 5, 7, 8, 9], 20)print(bubble_sort([1, 2, 3, 4, 5, 6, 7])) # (..., 6): best case O(n)print(bubble_sort(list(range(100, 0, -1)))[1]) # 4950 = 100 * 99 / 2Example 2
Selection sort
The selection sort cycle
Selection sort on [5, 3, 8, 1, 9, 2, 7]
| i | Scan length | Minimum found | Array after step |
|---|---|---|---|
| 0 | 6 | 1 at index 3: swap | [1, 3, 8, 5, 9, 2, 7] |
| 1 | 5 | 2 at index 5: swap | [1, 2, 8, 5, 9, 3, 7] |
| 2 | 4 | 3 at index 5: swap | [1, 2, 3, 5, 9, 8, 7] |
| 3 | 3 | 5 already in place | [1, 2, 3, 5, 9, 8, 7] |
| 4 | 2 | 7 at index 6: swap | [1, 2, 3, 5, 7, 8, 9] |
| 5 | 1 | 8 already in place | [1, 2, 3, 5, 7, 8, 9] |
Bubble sort against selection sort
| Bubble sort | Selection sort | |
|---|---|---|
| Comparisons (worst) | , every time | |
| Swaps (worst) | at most | |
| Best case | with an early exit | |
| Stable | Yes | No (a long-distance swap can reorder equal values) |
| Extra space |
Example 3
Checking every pair
Many brute-force solutions look at every pair: does any pair sum to a target, are any two values equal, which two points are closest? Starting the inner loop at visits each unordered pair exactly once.
How many pairs?
def pairs_with_sum(arr, target): found, checked = [], 0 for i in range(len(arr) - 1): for j in range(i + 1, len(arr)): # each pair once checked += 1 if arr[i] + arr[j] == target: found.append((arr[i], arr[j])) return found, checkeddef has_duplicate_naive(arr): for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[i] == arr[j]: return True return Falseprint(pairs_with_sum([5, 3, 8, 1, 9, 2, 7], 11)) # ([(3, 8), (9, 2)], 21)print(has_duplicate_naive([4, 1, 7, 1])) # TrueEscape hatch
Hashing turns all-pairs into O(n)
Two-sum in one pass with a set
Where the n² goes
One pass with a hash set or map
- Two-sum: look up
target - xin : total. - Contains duplicate: add to a set and check first: .
- Costs extra memory.
Nested loops over pairs
- Two-sum: try every pair: .
- Contains duplicate: compare every pair: .
- Fine for a few hundred items, hopeless for a million.
Escape strategies
| Problem | Naive | Better |
|---|---|---|
| Two-sum: find a pair with a given sum | nested loops | with a hash map |
| Contains duplicate | compare all pairs | with a set |
| Sorting | bubble or selection sort | merge sort, quicksort, Timsort |
| Closest pair of points | check every pair | divide and conquer |
| Pair sum on sorted data | nested loops | two pointers from both ends |
Pattern spotting
Spotting O(n²) in code
| Code shape | What it is | Cost |
|---|---|---|
for i in range(n): for j in range(n) | Full nested loops | |
for i in range(n): for j in range(i + 1, n) | Every pair once | , about |
for x in a: ... then for y in a: ... | Two loops in sequence | |
for x in a: for y in b | Two different inputs | |
for x in a: if x in some_list | Hidden scan inside a loop | |
for i in range(n): for k in range(5) | Inner loop is constant | |
for row in grid: for cell in row on an n × n grid | Every cell of a matrix |
Is this code quadratic?
Comparison
Quadratic next to its neighbours
| Class | Steps at n = 10,000 | Typical example |
|---|---|---|
| about 14 | Binary search | |
| 10,000 | One pass, hash-set two-sum | |
| about 133,000 | Merge sort, Timsort | |
| 100,000,000 | Bubble sort, selection sort, all pairs | |
| Three nested loops, naive matrix multiply |
Interview problems where O(n²) is the first answer
Two-sum
Brute force checks every pair; a hash map of seen values makes it .
Contains duplicate
Compare every pair, or put values in a set as you go.
Three-sum
Naive is . Sort, then two pointers for each element: , the accepted answer.
Longest palindromic substring
Expand around each of the centres: , a fine answer here.
In the wild
Where O(n²) shows up
Game collision checks
Testing every object against every other is tests; engines use spatial grids to cut it down.
Data cleaning
Deduplicating rows by comparing each with all others is quadratic; hashing a key per row is linear.
Similarity matrices
Comparing every document or user with every other builds an table.
Sorting short runs
Timsort sorts small runs with insertion sort, an method that is fast on tiny inputs.
Recap
Key takeaways
Key points
- O(n²) means the work grows with the square of , usually from a loop inside a loop over the same data.
- Every pair once costs , still after dropping the and the lower-order .
- Double the input, four times the work; ten times the input, a hundred times the work.
- Bubble and selection sort both make comparisons; selection sort swaps at most times, bubble sort can stop early on sorted data.
- A hash set or map replaces the inner search with an lookup and turns all-pairs problems into , at the cost of memory.
- Sequential loops add, nested loops multiply, and an call inside a loop is a hidden second loop.