Complexity Analysis

Time Complexity

Time complexity describes how the runtime of an algorithm scales with input size. It is the single most important tool for comparing and selecting data structures and algorithms.

How do you calculate time complexity?

Count how many basic steps the code performs as a function of the input size n, then keep only the fastest-growing term. A single loop over n items is O(n), a loop inside a loop over the same items is O(n²), and a loop that halves n each time is O(log n). Sequential steps add together and nested steps multiply.

function hasDuplicate(arr) {          // O(n²): nested loops
  for (let i = 0; i < arr.length; i++)
    for (let j = i + 1; j < arr.length; j++)
      if (arr[i] === arr[j]) return true;
  return false;
}
const hasDuplicateFast = (arr) => new Set(arr).size !== arr.length;   // O(n)

Race: watch complexity grow

Complexity Race

ConstantO(1)0 ops
LogarithmicO(log n)0 ops
LinearO(n)0 ops
LinearithmicO(n log n)0 ops
QuadraticO(n²)0 ops

Drag slider to change input size n, then race!

The complexity hierarchy

Hash table lookup, stack push/popO(1)

Constant time

Binary search, balanced BST operationsO(log n)

Logarithmic time

Linear scan, single loopO(n)

Linear time

Merge sort, heap sortO(n log n)

Linearithmic time

Bubble sort, nested loopsO(n²)

Quadratic time

Recursive Fibonacci, subset enumerationO(2ⁿ)

Exponential time

How to analyse code

1 / 4
1

Identify units of work

Find the operation that runs most often. Ignore constants and minor operations. Focus on what scales with input size n.

1 of 4

Loop patterns

loop-patterns.pseudo
1// Single loop → O(n)
2for i from 0 to n:
3 doWork(i)
4 
5// Nested loops → O(n²)
6for i from 0 to n:
7 for j from 0 to n:
8 doWork(i, j)
9 
10// Log loop — halving each time → O(log n)
11i = n
12while i > 1:
13 i = i / 2
⚠️Amortized complexity
Some operations are occasionally expensive but cheap on average. Dynamic array push is O(1) amortized even though resizing is O(n) — because resizing halves in frequency. Always think amortized for data structures with periodic bulk operations.

🎯 Quick Check

What is the time complexity of the following: for i in range(n): for j in range(i): work()?

Time Complexity: summary

Key points

  • Sequential blocks: O(a) + O(b). Nested blocks: O(a × b).
  • Recursion: multiply the number of calls by the work per call (naive Fibonacci is O(2ⁿ)).
  • Built-in methods have costs too: sort is O(n log n), shift and unshift are O(n).

Frequently asked questions

›What is the time complexity of a for loop?

O(n) if it runs n times doing constant work each time. Two nested loops over n items are O(n²).

›What is amortized time complexity?

The average cost per operation over a long sequence. array.push is O(1) amortized: occasionally it resizes (O(n)), but averaged over many pushes it's constant.