Big O notation cheat sheet for coding interviews
Big O notation describes how an algorithm's running time or memory grows as the input grows, ignoring constant factors and smaller terms. In coding interviews you are expected to state it for your solution, in time and in space, and to name the worst case unless you say otherwise. The common classes, from fastest to slowest growth, are O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ) and O(n!); this cheat sheet lists them with the costs of everyday data structure operations and the rules for deriving each one.
By Evin JohnPublished 9 min read
What the notation means
Formally, O(f(n)) is an upper bound: past some input size, the cost never exceeds a constant times f(n). Interviewers use it more loosely, to mean the tightest growth rate you can justify. If you say a loop is O(n³) when it is really O(n), you are technically right and still wrong for the conversation. Give the tight bound, and say whether it is the worst case, the average case, or an amortized cost spread over many operations.
Two quick conventions. n is the size of the main input, and you name any other size with its own letter: m edges, k results, L for string length. And the base of a logarithm does not matter inside Big O, because changing base only multiplies by a constant.
The growth classes
| Class | Name | Where it usually comes from | Example on this site |
|---|---|---|---|
| O(1) | Constant | Array index, hash map get and put on average, push and pop on a stack | LRU Cache operations |
| O(log n) | Logarithmic | Binary search, one heap push or pop, a balanced tree step | Adding a number in Find Median from Data Stream |
| O(n) | Linear | One pass over the input, building a hash map | Two Sum with a map |
| O(n log n) | Linearithmic | Comparison sorting, n heap operations | Merge Intervals, dominated by the sort |
| O(n²) | Quadratic | Every pair of elements, nested loops over the same input | Two Sum checking every pair |
| O(2ⁿ) | Exponential | Every subset, naive recursion with two branches | Subsets, times n to copy each one |
| O(n!) | Factorial | Every ordering | Permutations, times n to copy each one |
| n | log n | n log n | n² | 2ⁿ |
|---|---|---|---|---|
| 10 | 3.3 | 33 | 100 | 1,024 |
| 1,000 | 10 | about 10,000 | 1,000,000 | a 302-digit number |
| 1,000,000 | about 20 | about 20 million | 10¹² | out of reach |
Rules for deriving it
- Sequential steps add, then the biggest term wins. A sort followed by one pass is O(n log n + n), which is O(n log n).
- Nested loops multiply. An outer loop over n with an inner loop over n is O(n²). An inner loop that starts at i + 1 does about half the work, and half of n² is still O(n²).
- Halving or doubling gives a logarithm. A loop where the range shrinks by half each time runs about log₂ n times.
- Different inputs keep their own letters. Comparing every word in list A with every word in list B is O(a · b). Walking a graph is O(V + E), not O(V).
- Recursion: count the calls, then the work per call. A function that calls itself twice on n - 1 makes about 2ⁿ calls. One that halves the input and does linear work at each level does O(n) work on each of log n levels, so O(n log n).
- Hidden loops count. Slicing a list, joining strings, checking membership in a list, and copying a path into the answer are all linear in what they touch.
| Recurrence | Result | Typical algorithm |
|---|---|---|
| T(n) = T(n/2) + O(1) | O(log n) | Binary search |
| T(n) = T(n/2) + O(n) | O(n) | Quickselect with lucky pivots (the work halves each round) |
| T(n) = 2T(n/2) + O(1) | O(n) | Visiting every node of a balanced tree |
| T(n) = 2T(n/2) + O(n) | O(n log n) | Merge sort |
| T(n) = T(n - 1) + O(n) | O(n²) | Selection sort, or quicksort with bad pivots every time |
| T(n) = 2T(n - 1) + O(1) | O(2ⁿ) | Plain recursive Fibonacci-style branching |
Costs of common data structure operations
| Structure | Access or search | Insert | Delete | Notes |
|---|---|---|---|---|
| Dynamic array (Python list, JS array) | Index O(1), search O(n) | End O(1) amortized, front or middle O(n) | End O(1), front or middle O(n) | Appends double the capacity now and then, so the average stays constant |
| Hash map or set | O(1) average (O(n)) | O(1) average (O(n)) | O(1) average (O(n)) | Worst case comes from many keys colliding |
| Binary heap | Peek O(1), search O(n) | O(log n) | Pop top O(log n) | Building a heap from n items at once is O(n) |
| Balanced search tree | O(log n) | O(log n) | O(log n) | Neither Python nor JavaScript ships one in the standard library |
| Sorted array with binary search | O(log n) | O(n) | O(n) | Python's bisect finds the spot fast, but shifting elements is linear |
| Linked list | O(n) | O(1) with a pointer to the spot | O(1) with a pointer to the node | Finding the spot is the O(n) part |
| Deque (Python collections.deque) | Ends O(1), middle O(n) | Either end O(1) | Either end O(1) | The right queue for BFS in Python |
Language traps worth knowing
- Python: list.pop(0) and list.insert(0, x) shift every element, so they are O(n). Use collections.deque for a queue. Testing x in a list is O(n); in a set or dict it is O(1) on average. Building a string with += in a loop can turn quadratic, because strings are immutable; collect pieces and call join once.
- JavaScript: Array shift and unshift generally move every element, so treat them as O(n), even though engines can optimize some cases. For a long BFS queue, keep a head index instead of shifting. The language specification only promises that Map and Set lookups are sublinear on average; engines use hash tables, so O(1) average is the usual working assumption.
- Sorting: Python's built-in sort is a stable merge-based sort that is O(n log n) in the worst case and close to linear on input that is already nearly sorted. JavaScript's specification requires a stable sort but does not name the algorithm; the major engines use O(n log n) sorts. Without a comparator, JavaScript sorts numbers as strings, which is a correctness bug rather than a speed issue.
Sorting algorithms at a glance
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) stack on average | No |
| Heapsort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes, when done with prefix counts |
| Radix sort (d digits) | O(d · (n + b)) | O(d · (n + b)) | O(d · (n + b)) | O(n + b) | Yes |
No comparison sort can beat O(n log n) in the worst case, which is why counting and bucket ideas matter: they avoid comparisons by using the values themselves. Top K Frequent Elements uses buckets indexed by frequency to get a linear answer, and Kth Largest Element in an Array uses quickselect for linear time on average.
Space complexity
- Count every structure you allocate that grows with the input: maps, sets, copies, the queue in a BFS.
- Count the call stack. A recursive DFS on a path-shaped graph or a skewed tree is O(n) deep, which also risks a stack overflow in Python at its default recursion limit.
- The memory needed for the answer itself is usually reported separately. Saying "O(1) extra space, not counting the output" is clearer than either number alone.
- In-place algorithms that modify the input are O(1) extra space, but mention that you are mutating the caller's data.
A template for checking your estimate
You can sanity-check an estimate in two ways. The first is to count steps for a few input sizes and watch the pattern. The second is a doubling test: time the function at n and at 2n. A ratio near 2 points to linear work, a bit above 2 to n log n, and near 4 to quadratic. Timings are noisy, so take the best of several runs and use sizes large enough to take a few milliseconds.
def count_steps(n):
square = 0
for i in range(n):
for j in range(n):
square += 1 # n * n steps
triangle = 0
for i in range(n):
for j in range(i + 1, n):
triangle += 1 # n(n - 1) / 2 steps, still O(n^2)
halving = 0
k = n
while k > 1:
k //= 2
halving += 1 # about log2(n) steps
return square, triangle, halving
for n in (8, 16, 32, 64):
print(n, count_steps(n))| n | Full nested loop | Loop from i + 1 | Halving loop |
|---|---|---|---|
| 8 | 64 | 28 | 3 |
| 16 | 256 | 120 | 4 |
| 32 | 1,024 | 496 | 5 |
| 64 | 4,096 | 2,016 | 6 |
Each doubling of n multiplies both nested counts by about 4 and adds 1 to the halving count. That is what O(n²) and O(log n) look like in practice.
import random
import time
def best_time(fn, n, repeats=5):
best = float("inf")
for _ in range(repeats):
data = [random.random() for _ in range(n)]
start = time.perf_counter()
fn(data)
best = min(best, time.perf_counter() - start)
return best
def doubling_ratio(fn, n):
# roughly 2 means linear, a little over 2 means n log n, roughly 4 means quadratic
return best_time(fn, 2 * n) / best_time(fn, n)
def all_pairs(data):
count = 0
for i in range(len(data)):
for j in range(i + 1, len(data)):
if data[i] < data[j]:
count += 1
return count
print("sum ", round(doubling_ratio(sum, 200_000), 1))
print("sorted ", round(doubling_ratio(sorted, 200_000), 1))
print("pairs ", round(doubling_ratio(all_pairs, 800), 1))function countSteps(n) {
let square = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) square++;
}
let halving = 0;
for (let k = n; k > 1; k = Math.floor(k / 2)) halving++;
return { square, halving };
}
function bestTime(fn, n, repeats = 5) {
let best = Infinity;
for (let r = 0; r < repeats; r++) {
const data = Array.from({ length: n }, () => Math.random());
const start = performance.now();
fn(data);
best = Math.min(best, performance.now() - start);
}
return best;
}
function doublingRatio(fn, n) {
return bestTime(fn, 2 * n) / bestTime(fn, n);
}
console.log(countSteps(64));
const sortCopy = (a) => a.slice().sort((x, y) => x - y);
console.log("sort ratio", doublingRatio(sortCopy, 200000).toFixed(1));On the machine used to write this page, the Python ratios came out near 2 for sum, slightly above 2 for sorted and near 4 for the all-pairs loop, as expected. Your numbers will differ, and very small inputs mostly measure overhead.
Input size as a hint
When a problem states its limits, the limits suggest the intended complexity. The guide below is a rough planning aid many people use, not a measurement, and the true budget depends on the language and the judge.
| Largest n | Complexity that usually fits | Typical technique |
|---|---|---|
| About 10 | O(n!) | Try every ordering |
| About 20 | O(2ⁿ) or O(n · 2ⁿ) | Subsets, bitmask DP |
| A few hundred | O(n³) | Triple loops, interval DP |
| A few thousand | O(n²) | All pairs, 2D DP |
| Hundreds of thousands to a few million | O(n log n) or O(n) | Sorting, heaps, hashing, two pointers, prefix sums |
| Larger, or many queries | O(log n) or O(1) per query | Binary search, precomputed tables |
Practice the analysis on real problems
- Two Sum: O(n²) pairs to O(n) with a map. Practice saying the space trade.
- Number of Islands: O(rows · cols), not O(n²); name both dimensions.
- Binary Tree Level Order Traversal: O(n) time, with queue space set by the widest level.
- Find Median from Data Stream: O(log n) per insert, O(1) per query.
- Prefix sum pattern: O(n) setup buys O(1) range queries.
- Swim in Rising Water: O(n² log n) for a grid with n² cells, a common place to drop a factor.
Mistakes that cost points
- Calling a hash map solution O(1) overall. It is O(1) per operation; doing n of them is O(n).
- Writing O(n) for a grid or a graph without saying what n is.
- Forgetting the sort. Sorting first makes the whole solution at least O(n log n).
- Ignoring the cost of copying: building each subset or path in the output adds a factor of its length.
- Quoting the average case of quicksort or hashing as if it were a guarantee.
- Leaving out the recursion stack when asked for space.
How to explain it out loud
Fictional example
- Interviewer
- What's the complexity?
- Candidate
- Sorting the n intervals is n log n. The scan after it touches each interval once, so it's linear, and the sort dominates. Overall O(n log n) time.
- Candidate
- For space, the sort in Python needs up to linear extra memory, and the output can hold n intervals in the worst case. Not counting the output, it's O(n) extra because of the sort.
- Interviewer
- Could you do better?
- Candidate
- Not with comparisons in general, since the answer depends on order. If the start times were small integers, I could bucket them and get closer to linear.
Checking your analysis with Natively
A useful drill is to work out the complexity yourself first and only then ask for a second opinion. Natively can read a problem from a screenshot on Mac or Windows and write an approach and code in its overlay, so you can hold its solution against your own analysis and catch a missed factor. In a spoken mock it transcribes what you said, which helps when you want to hear whether you stated worst case or average case. More about the AI interview assistant.
Questions people ask
What is Big O notation in simple terms?
It describes how the time or memory an algorithm needs grows as the input grows, ignoring constant factors and smaller terms. O(n) grows in step with the input; O(n²) grows with its square.
What is the time complexity of a hash map lookup?
O(1) on average and O(n) in the worst case, when many keys collide. In interviews, say "O(1) average" rather than just O(1).
Is O(n log n) faster than O(n)?
No. O(n log n) grows a little faster than O(n), so it is slower for large inputs. It is much better than O(n²), and it is the cost of comparison sorting.
Do you count the output in space complexity?
Usually not. State it explicitly, for example "O(1) extra space, not counting the output", and include the recursion stack if your solution recurses.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
