AlgoViz

O(n²) quadratic time

easy 14 min

O(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

0:00 / 4:09

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.

Step 1 of 3

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 nn items, do something with each of the nn 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 nn inside a loop of nn runs its body n×n=n2n \times n = n^2 times.

  • Double n, four times the work

    (2n)2=4n2(2n)^2 = 4n^2. 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 O(n)O(n) or O(nlog⁡n)O(n \log n).

The core count

n⏟outer loop×n⏟inner loop=n2 operations\underbrace{n}_{\text{outer loop}} \times \underbrace{n}_{\text{inner loop}} = n^2 \text{ operations}
Each pass of the outer loop pays for a full run of the inner loop. Nested loops multiply; loops placed one after another add.

The pattern

The nested loop

Python
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, 1000000
Count how many times the inner body runs. For n = 4 it is 16; for n = 1,000 it is a million.
Edit and run it in your browser

How two nested loops run

The inner loop restarts from scratch for every value of ii. That restart is where the second factor of nn comes from.

The math

Counting the triangle

Most quadratic algorithms do not run the inner loop a full nn times. Bubble sort, selection sort and the all-pairs check all start the inner loop later each round, so the work forms a triangle: n−1n - 1 steps, then n−2n - 2, down to 1. Add them up with the arithmetic series formula.

The sum behind every pair loop

∑i=1n−1i=1+2+⋯+(n−1)=n(n−1)2\sum_{i=1}^{n-1} i = 1 + 2 + \cdots + (n-1) = \frac{n(n-1)}{2}
Pair the first and last terms: 1+(n−1)=n1 + (n-1) = n, 2+(n−2)=n2 + (n-2) = n, and so on. There are (n−1)/2(n-1)/2 such pairs, each worth nn. For n=7n = 7: 6+5+4+3+2+1=21=7⋅626 + 5 + 4 + 3 + 2 + 1 = 21 = \frac{7 \cdot 6}{2}.

Why that is still O(n²)

n(n−1)2=12n2−12nandn24≤n(n−1)2≤n2 for n≥2\frac{n(n-1)}{2} = \frac{1}{2}n^2 - \frac{1}{2}n \quad\text{and}\quad \frac{n^2}{4} \le \frac{n(n-1)}{2} \le n^2 \text{ for } n \ge 2
Big O drops the constant 12\tfrac12 and the lower-order term 12n\tfrac12 n. The count is squeezed between two multiples of n2n^2, so it is Θ(n2)\Theta(n^2): skipping half the pairs halves the time but does not change the growth.

Inner loop runs for n = 7 (j from i + 1)

Outer i012345Total
Inner runs65432121
With range(n) for both loops you would get 7×7=497 \times 7 = 49; starting at i+1i + 1 gives 21. Both are O(n2)O(n^2).

Scale

The danger zone

nO(n)O(n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)n2n^2 at 1 µs per step
1010331000.1 ms
10010066410,00010 ms
1,0001,000about 10,0001,000,0001 second
10,00010,000about 133,00010810^8about 1.7 minutes
100,000100,000about 1.7 million101010^{10}about 2.8 hours
1,000,0001,000,000about 20 million101210^{12}about 11.6 days
At a million items the quadratic algorithm needs a trillion steps. The O(nlog⁡n)O(n \log n) one needs 20 million, about 20 seconds at the same speed.

Scaling the input

T(kn)=(kn)2=k2⋅n2k=2⇒4×,k=10⇒100×T(kn) = (kn)^2 = k^2 \cdot n^2 \qquad k = 2 \Rightarrow 4\times, \quad k = 10 \Rightarrow 100\times
If sorting 100 items with an O(n2)O(n^2) sort takes 1 second, 1,000 items take about 100 seconds.

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 n−1n - 1 comparisons, pass 2 makes n−2n - 2, and so on: n(n−1)2\frac{n(n-1)}{2} in total. On [5, 3, 8, 1, 9, 2, 7] that is 21 comparisons and 10 swaps.

One pass of bubble sort

The outer loop repeats this pass n−1n - 1 times, each one a cell shorter.
Python
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 / 2
Bubble sort with a comparison counter and an early exit when a pass makes no swaps.
Edit and run it in your browser

Example 2

Selection sort

The selection sort cycle

The scan always looks at every unsorted cell, even when the minimum is already at position ii.

Selection sort on [5, 3, 8, 1, 9, 2, 7]

iScan lengthMinimum foundArray after step
061 at index 3: swap[1, 3, 8, 5, 9, 2, 7]
152 at index 5: swap[1, 2, 8, 5, 9, 3, 7]
243 at index 5: swap[1, 2, 3, 5, 9, 8, 7]
335 already in place[1, 2, 3, 5, 9, 8, 7]
427 at index 6: swap[1, 2, 3, 5, 7, 8, 9]
518 already in place[1, 2, 3, 5, 7, 8, 9]
21 comparisons and 4 swaps. The comparisons would be 21 for any input of 7 values.

Bubble sort against selection sort

Bubble sortSelection sort
Comparisons (worst)n(n−1)2\frac{n(n-1)}{2}n(n−1)2\frac{n(n-1)}{2}, every time
Swaps (worst)n(n−1)2\frac{n(n-1)}{2}at most n−1n - 1
Best caseO(n)O(n) with an early exitO(n2)O(n^2)
StableYesNo (a long-distance swap can reorder equal values)
Extra spaceO(1)O(1)O(1)O(1)

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 i+1i + 1 visits each unordered pair exactly once.

How many pairs?

(n2)=n(n−1)2n=7⇒21,n=10⇒45,n=1,000⇒499,500\binom{n}{2} = \frac{n(n-1)}{2} \qquad n = 7 \Rightarrow 21, \quad n = 10 \Rightarrow 45, \quad n = 1{,}000 \Rightarrow 499{,}500
Choose 2 items out of nn. It is the same triangle sum as before, so checking all pairs is O(n2)O(n^2).
Python
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]))          # True
Brute force on [5, 3, 8, 1, 9, 2, 7] with target 11: 21 checks find (3, 8) and (9, 2).
Edit and run it in your browser

Escape hatch

Hashing turns all-pairs into O(n)

Two-sum in one pass with a set

The inner loop that searched for a partner is replaced by one hash lookup. On [5, 3, 8, 1, 9, 2, 7] with target 11, it finds both pairs with 7 lookups instead of 21 checks.

Where the n² goes

n⏟values×O(n)⏟scan for partner=O(n2)⟶n⏟values×O(1)⏟hash lookup=O(n)\underbrace{n}_{\text{values}} \times \underbrace{O(n)}_{\text{scan for partner}} = O(n^2) \quad\longrightarrow\quad \underbrace{n}_{\text{values}} \times \underbrace{O(1)}_{\text{hash lookup}} = O(n)
The trade is memory for time: the set holds up to nn values, so space goes from O(1)O(1) to O(n)O(n). Hash lookups are O(1)O(1) on average.

One pass with a hash set or map

  • Two-sum: look up target - x in O(1)O(1): O(n)O(n) total.
  • Contains duplicate: add to a set and check first: O(n)O(n).
  • Costs O(n)O(n) extra memory.

Nested loops over pairs

  • Two-sum: try every pair: O(n2)O(n^2).
  • Contains duplicate: compare every pair: O(n2)O(n^2).
  • Fine for a few hundred items, hopeless for a million.

Escape strategies

ProblemNaiveBetter
Two-sum: find a pair with a given sumO(n2)O(n^2) nested loopsO(n)O(n) with a hash map
Contains duplicateO(n2)O(n^2) compare all pairsO(n)O(n) with a set
SortingO(n2)O(n^2) bubble or selection sortO(nlog⁡n)O(n \log n) merge sort, quicksort, Timsort
Closest pair of pointsO(n2)O(n^2) check every pairO(nlog⁡n)O(n \log n) divide and conquer
Pair sum on sorted dataO(n2)O(n^2) nested loopsO(n)O(n) two pointers from both ends
When you see O(n2)O(n^2), ask: can a hash map, sorting, or two pointers remove the inner loop?

Pattern spotting

Spotting O(n²) in code

Code shapeWhat it isCost
for i in range(n): for j in range(n)Full nested loopsO(n2)O(n^2)
for i in range(n): for j in range(i + 1, n)Every pair onceO(n2)O(n^2), about n2/2n^2/2
for x in a: ... then for y in a: ...Two loops in sequenceO(n)O(n)
for x in a: for y in bTwo different inputsO(n⋅m)O(n \cdot m)
for x in a: if x in some_listHidden scan inside a loopO(n2)O(n^2)
for i in range(n): for k in range(5)Inner loop is constantO(n)O(n)
for row in grid: for cell in row on an n × n gridEvery cell of a matrixO(n2)O(n^2)

Is this code quadratic?

Count how many times the innermost line runs as a function of nn. The shape of the code is only a hint.

Comparison

Quadratic next to its neighbours

ClassSteps at n = 10,000Typical example
O(log⁡n)O(\log n)about 14Binary search
O(n)O(n)10,000One pass, hash-set two-sum
O(nlog⁡n)O(n \log n)about 133,000Merge sort, Timsort
O(n2)O(n^2)100,000,000Bubble sort, selection sort, all pairs
O(n3)O(n^3)101210^{12}Three nested loops, naive matrix multiply
At ten thousand items the jump from nlog⁡nn \log n to n2n^2 is a factor of about 750.

Interview problems where O(n²) is the first answer

  • Two-sum

    Brute force checks every pair; a hash map of seen values makes it O(n)O(n).

  • Contains duplicate

    Compare every pair, or put values in a set as you go.

  • Three-sum

    Naive is O(n3)O(n^3). Sort, then two pointers for each element: O(n2)O(n^2), the accepted answer.

  • Longest palindromic substring

    Expand around each of the 2n−12n - 1 centres: O(n2)O(n^2), a fine answer here.

In the wild

Where O(n²) shows up

  • Game collision checks

    Testing every object against every other is n2/2n^2/2 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 n×nn \times n table.

  • Sorting short runs

    Timsort sorts small runs with insertion sort, an O(n2)O(n^2) method that is fast on tiny inputs.

Recap

Key takeaways

Key points

  • O(n²) means the work grows with the square of nn, usually from a loop inside a loop over the same data.
  • Every pair once costs ∑i=1n−1i=n(n−1)2\sum_{i=1}^{n-1} i = \frac{n(n-1)}{2}, still O(n2)O(n^2) after dropping the 12\tfrac12 and the lower-order nn.
  • Double the input, four times the work; ten times the input, a hundred times the work.
  • Bubble and selection sort both make n(n−1)2\frac{n(n-1)}{2} comparisons; selection sort swaps at most n−1n - 1 times, bubble sort can stop early on sorted data.
  • A hash set or map replaces the inner search with an O(1)O(1) lookup and turns all-pairs problems into O(n)O(n), at the cost of O(n)O(n) memory.
  • Sequential loops add, nested loops multiply, and an O(n)O(n) call inside a loop is a hidden second loop.

Sources