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.
See it run
Watch bubble sort, selection sort and a brute-force pair check each do about n²/2 comparisons, then see n² pull away from n log n.
Operations
Bubble sort
Sort [5, 3, 8, 1, 9, 2, 7] by comparing neighbours and swapping when they are out of order. Each pass carries the largest unsorted value to the end.
Step 1 of 12
Seven unsorted values
- 50
- 31
- 82
- 13
- 94
- 25
- 76
Bubble sort runs two nested loops. The outer loop makes n - 1 = 6 passes; the inner loop compares each neighbour pair in the unsorted part and swaps if the left one is bigger.
Step 1: Seven unsorted values
def bubble_sort(arr): n = len(arr) comparisons = 0 for i in range(n - 1): # pass i fixes one more cell at the end for j in range(n - 1 - i): # walk the unsorted part comparisons += 1 if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr, comparisons- Time
- O(n²)
- Space
- O(1)
- comparisons
- n(n-1)/2 = 21 for n = 7
- swaps
- up to n(n-1)/2, here 10
Each pass of bubble sort fixes exactly one value at the end. n - 1 passes of shrinking length add up to n(n-1)/2 comparisons, which is O(n²).
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Hidden O(n) inside a loop
criticalx in some_listscans the list, so doing it inside a loop over n items is O(n²) even though only one loop is visible. A set makes each membership test O(1) on average.Wrongunique = []for x in items: if x not in unique: # scans unique: O(n) unique.append(x)Rightseen, unique = set(), []for x in items: if x not in seen: # O(1) average seen.add(x) unique.append(x)Starting the inner loop at 0 for pairs
majorWith
jstarting at 0, every pair is checked twice and each value is paired with itself, so a single 4 with target 8 matches itself as 4 + 4, and every real pair is reported twice.Wrongfor i in range(n): for j in range(n): # (i, i) and (j, i) too if arr[i] + arr[j] == target: ...Rightfor i in range(n): for j in range(i + 1, n): # each pair once, never itself if arr[i] + arr[j] == target: ...Removing from the front of a list in a loop
majorlist.pop(0)andlist.insert(0, x)shift every other element, so each is O(n). Doing it n times is O(n²). A deque does both ends in O(1).Wrongqueue = list(tasks)while queue: task = queue.pop(0) # O(n) shift each timeRightfrom collections import dequequeue = deque(tasks)while queue: task = queue.popleft() # O(1)Building a list by copying it each time
majorresult = result + [x]creates a brand-new list of growing length on every iteration: 1 + 2 + ... + n copies, which is O(n²).appendis amortised O(1).Wrongresult = []for x in data: result = result + [x] # copies the whole listRightresult = []for x in data: result.append(x) # amortised O(1)Bubble sort without an early exit
minorThe plain version always runs n - 1 passes, even on sorted input. A
swappedflag stops as soon as a pass makes no swaps, giving O(n) on already-sorted data. The worst case stays O(n²).Wrongfor i in range(n - 1): for j in range(n - 1 - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j]Rightfor i in range(n - 1): swapped = False for j in range(n - 1 - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: break
Interview tips
How to explain it
- O(n²) means the work grows with the square of the input, usually from two nested loops over the same data.
- Checking every pair costs n(n-1)/2, and dropping the constant 1/2 and the lower-order n leaves O(n²).
- Double the input and the time goes up four times; ten times the input costs a hundred times the time.
- Name the fix: a hash map or set for lookups, or sorting first, usually gets you to O(n) or O(n log n).
Spot it in code
- `for i in range(n): for j in range(n)` or `range(i + 1, n)`: quadratic either way.
- Two loops one after the other are O(n) + O(n) = O(n), not O(n²).
- `x in list`, `list.pop(0)` or `s.index(x)` inside a loop hides a second O(n).
- Nested loops over two different inputs are O(n · m), not O(n²).
Memory tricks
- The dance floor: everyone dances with everyone, so n people make about n² / 2 pairs.
- Handshakes: n people each shake n - 1 hands, and each shake is counted twice: n(n-1)/2.
- City grid: n streets times n avenues gives n² corners.
- 2n → 4n², 10n → 100n².
Watch out
- O(n²) is often fine for small n: insertion sort beats merge sort on a dozen items.
- The hash-set fix costs O(n) extra memory; say so when you propose it.
- Not every nested loop is O(n²): an inner loop that runs a constant or log n times is not.