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
Drag slider to change input size n, then race!
The complexity hierarchy
Constant time
Logarithmic time
Linear time
Linearithmic time
Quadratic time
Exponential time
How to analyse code
Identify units of work
Find the operation that runs most often. Ignore constants and minor operations. Focus on what scales with input size n.
Loop patterns
1// Single loop → O(n)2for i from 0 to n:3 doWork(i)45// Nested loops → O(n²)6for i from 0 to n:7 for j from 0 to n:8 doWork(i, j)910// Log loop — halving each time → O(log n)11i = n12while i > 1:13 i = i / 2
🎯 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:
sortis O(n log n),shiftandunshiftare 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.