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 Published 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

From slowest growth to fastest, with a typical source of each
ClassNameWhere it usually comes fromExample on this site
O(1)ConstantArray index, hash map get and put on average, push and pop on a stackLRU Cache operations
O(log n)LogarithmicBinary search, one heap push or pop, a balanced tree stepAdding a number in Find Median from Data Stream
O(n)LinearOne pass over the input, building a hash mapTwo Sum with a map
O(n log n)LinearithmicComparison sorting, n heap operationsMerge Intervals, dominated by the sort
O(n²)QuadraticEvery pair of elements, nested loops over the same inputTwo Sum checking every pair
O(2ⁿ)ExponentialEvery subset, naive recursion with two branchesSubsets, times n to copy each one
O(n!)FactorialEvery orderingPermutations, times n to copy each one
From slowest growth to fastest, with a typical source of each. Scroll sideways on a small screen.
How the counts grow (log base 2, rounded)
nlog nn log nn²2ⁿ
103.3331001,024
1,00010about 10,0001,000,000a 302-digit number
1,000,000about 20about 20 million10¹²out of reach
How the counts grow (log base 2, rounded). Scroll sideways on a small screen.

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.
Recurrences that cover most interview recursion
RecurrenceResultTypical 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
Recurrences that cover most interview recursion. Scroll sideways on a small screen.

Costs of common data structure operations

Typical costs; worst cases in brackets where they differ
StructureAccess or searchInsertDeleteNotes
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 setO(1) average (O(n))O(1) average (O(n))O(1) average (O(n))Worst case comes from many keys colliding
Binary heapPeek 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 treeO(log n)O(log n)O(log n)Neither Python nor JavaScript ships one in the standard library
Sorted array with binary searchO(log n)O(n)O(n)Python's bisect finds the spot fast, but shifting elements is linear
Linked listO(n)O(1) with a pointer to the spotO(1) with a pointer to the nodeFinding 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
Typical costs; worst cases in brackets where they differ. Scroll sideways on a small screen.

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

Comparison sorts plus the two non-comparison ones that come up
AlgorithmBestAverageWorstExtra spaceStable
Insertion sortO(n)O(n²)O(n²)O(1)Yes
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
QuicksortO(n log n)O(n log n)O(n²)O(log n) stack on averageNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)No
Counting sortO(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
Comparison sorts plus the two non-comparison ones that come up. Scroll sideways on a small screen.

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))
Count the steps of three loop shapes.
Output of the step counter above
nFull nested loopLoop from i + 1Halving loop
864283
162561204
321,0244965
644,0962,0166
Output of the step counter above. Scroll sideways on a small screen.

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))
Doubling test: best of five runs at n and 2n.
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));
The same two checks in JavaScript, using performance.now().

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.

Rough fit between input size and complexity
Largest nComplexity that usually fitsTypical technique
About 10O(n!)Try every ordering
About 20O(2ⁿ) or O(n · 2ⁿ)Subsets, bitmask DP
A few hundredO(n³)Triple loops, interval DP
A few thousandO(n²)All pairs, 2D DP
Hundreds of thousands to a few millionO(n log n) or O(n)Sorting, heaps, hashing, two pointers, prefix sums
Larger, or many queriesO(log n) or O(1) per queryBinary search, precomputed tables
Rough fit between input size and complexity. Scroll sideways on a small screen.

Practice the analysis on real problems

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

Stating the cost after a sort-then-scan solution
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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP