HomeCoursesBlog
← Back to Blog
Article

Big O Cheat Sheet: Time and Space Complexity for Every Coding Pattern

Big O Cheat Sheet: Time and Space Complexity for Every Coding Pattern

TL;DR: Big O describes how an algorithm's running time or memory grows as the input grows. In an interview, it does two jobs. Before you code, the input limits tell you which complexity the intended solution has, and therefore which patterns are possible. After you code, you state the time and space of your solution and explain where each term comes from. This page gives the complexity classes, the input size each class can handle, the cost of every common data structure operation, and the time and space of each common coding pattern, in tables you can scan in a minute.

What Big O notation means

Big O notation describes how the cost of an algorithm grows as the input size, written n, grows. It keeps only the fastest-growing term and drops constant factors, so an algorithm that takes 3n + 20 steps is O(n), and one that takes n squared plus n steps is O(n^2).

Two kinds of cost matter. Time complexity counts the steps the algorithm takes. Space complexity counts the extra memory it uses beyond the input, which interviewers usually call auxiliary space. A complete answer in an interview always states both.

Big O is an upper bound on growth, and in interviews it almost always means the worst case. When the average case is different, as it is for hash maps and quicksort, say both and name which one you mean.

The complexity classes, fastest to slowest

ComplexityNameWhat it looks likeTypical example
O(1)ConstantA fixed number of steps, whatever n isHash map lookup, array index
O(log n)LogarithmicThe problem halves at each stepBinary search
O(n)LinearOne pass, or a fixed number of passesSliding window, counting with a hash map
O(n log n)LinearithmicSorting, or n operations on a heap of size nMerge sort, sort then sweep
O(n^2)QuadraticA loop inside a loop over the same inputComparing every pair
O(n^3)CubicThree nested loopsSome interval dynamic programming
O(2^n)ExponentialEvery element is either in or outGenerating all subsets
O(n!)FactorialEvery ordering of the elementsGenerating all permutations

The input size each complexity allows

A typical judge runs on the order of 100 million simple operations per second, and most problems have a limit of one or two seconds. Read the constraint on n before you design anything, because it narrows the possible solutions before you have read the examples.

Big O by input size: n up to about 10 means O(n!) is acceptable, up to about 20 means O(2^n), up to about 500 means O(n^3), up to about 5,000 means O(n^2), up to about one million means O(n log n), and up to about 100 million means O(n)

Largest n in the constraintsComplexity that fitsPatterns that usually match
about 10O(n!)Backtracking over permutations
about 20O(2^n)Subsets, backtracking with pruning, bitmask DP
about 500O(n^3)Interval DP, three nested loops
about 5,000O(n^2)Two-dimensional DP, comparing pairs
about 1,000,000O(n log n)Sorting, heaps, binary search inside a loop
about 100,000,000O(n)One pass with two pointers, a window, or a hash map
larger than thatO(log n) or O(1)Binary search on the answer, a formula

These limits are a rough guide, not a rule. A slow language, a large constant factor, or many test cases in one input can lower them. But when a problem allows n up to 100,000, an O(n^2) solution will almost always time out, and the intended solution is O(n log n) or better.

Data structure operations

Data structureAccess or lookupInsertDeleteNotes
Array or dynamic arrayO(1) by indexO(1) amortized at the end, O(n) in the middleO(1) at the end, O(n) in the middleSearch for a value is O(n)
Hash map or hash setO(1) averageO(1) averageO(1) averageO(n) in the rare worst case of many collisions
Linked listO(n) to find a nodeO(1) at a known nodeO(1) at a known nodeFinding the node is the O(n) part
Stack or queueO(1) for the top or frontO(1)O(1)Use a deque for a queue in Python
Binary heapO(1) to read the minimumO(log n)O(log n) to remove the minimumBuilding a heap from n items is O(n)
Balanced binary search tree or ordered setO(log n)O(log n)O(log n)Keeps items sorted at all times
Sorted arrayO(log n) with binary searchO(n)O(n)Cheap to search, expensive to change
TrieO(L) for a word of length LO(L)O(L)Cost depends on word length, not word count
Union-findnearly O(1) amortizednearly O(1)not supportedWith path compression and union by rank

Amortized means averaged over a long sequence of operations. Appending to a dynamic array sometimes copies the whole array into a larger one, which costs O(n), but that happens so rarely that the average cost per append stays O(1).

Time and space complexity of every common coding pattern

The table below covers the common patterns in the order the DSA patterns cheat sheet teaches them. The complexity is the typical one for the standard form of each pattern, with n as the input size. A specific problem can add a sort or a larger output, so always check the extra steps your version adds.

PatternTypical timeTypical extra spaceWhere the cost comes from
Two PointersO(n), or O(n log n) with a sort firstO(1)Each pointer moves across the input once
Fast and Slow PointersO(n)O(1)The fast pointer reaches the end or meets the slow one within a linear number of steps
Sliding WindowO(n)O(1), or O(k) for a counter of the window's contentsEach element enters and leaves the window once
Merge IntervalsO(n log n)O(n) for the outputThe sort dominates the single sweep
Cyclic SortO(n)O(1)Each swap puts one number in its final place
In-place Reversal of a Linked ListO(n)O(1)One pass, rewiring pointers as it goes
StacksO(n)O(n)Each item is pushed and popped at most once
Monotonic StackO(n)O(n)Each element is pushed once and popped at most once
Hash MapsO(n)O(n)One pass with constant-time lookups
Tree Level Order Traversal (BFS)O(n)O(w), where w is the widest levelThe queue holds one level at a time
Tree DFSO(n)O(h), where h is the tree heightThe recursion stack holds one root-to-leaf path
Graphs (BFS and DFS)O(V + E)O(V)Every vertex and every edge is processed once
Matrix TraversalO(m × n)O(m × n) in the worst caseEach cell is visited once
Two HeapsO(log n) per insert, O(1) to read the medianO(n)Each insert rebalances two heaps
SubsetsO(n × 2^n)O(n × 2^n) for the outputThere are 2^n subsets, each up to n long
Modified Binary SearchO(log n)O(1)The search range halves at each step
Binary Search on the AnswerO(n log R), where R is the answer rangeO(1)An O(n) check runs once per halving of the range
Bitwise XORO(n)O(1)One pass, folding values into one number
Top 'K' ElementsO(n log k)O(k)Each element costs one heap operation on a heap of size k
K-way MergeO(N log k) for N total elementsO(k)The heap holds only the k current heads
GreedyO(n log n) when it sorts first, otherwise O(n)O(1)The sort usually dominates
0/1 KnapsackO(n × C), where C is the capacityO(C) with a one-row tableOne cell per item and capacity pair
Fibonacci-style DPO(n)O(1) with two variablesEach state depends on a fixed number of earlier states
Palindromic SubsequenceO(n^2)O(n^2), or O(n) with a rolling rowOne cell per pair of string positions
BacktrackingO(n × n!) for permutations, O(n × 2^n) for subsetsO(n) for the recursion, plus the outputThe number of complete candidates sets the cost
TrieO(L) per insert or searchO(total characters stored)Each character is one step down the tree
Topological SortO(V + E)O(V + E)Each vertex and edge is processed once
Union Findnearly O(1) amortized per operationO(n)Path compression keeps the trees almost flat
Ordered SetO(log n) per operationO(n)A balanced tree keeps items sorted
Prefix SumO(n) to build, O(1) per range queryO(n)One pass builds the running totals

The Multi-threaded pattern is missing from this table on purpose. Its interview questions are about correctness under concurrency, such as locks and ordering, rather than about growth with n.

Complexity of recursion and dynamic programming

The cost of recursive code is not visible in a single loop, so it needs a method of its own.

Recursion without memoization. The cost is roughly the number of branches raised to the depth of the recursion. A function that calls itself twice on n minus 1, such as naive Fibonacci, makes about 2^n calls.

Recursion with memoization, and dynamic programming. The cost is the number of distinct states multiplied by the work per state. Fibonacci with memoization has n states with constant work each, so it is O(n). Longest common subsequence has m × n states with constant work each, so it is O(m × n).

Divide and conquer. When a function splits the input in half, recurses on both halves, and does linear work to combine them, the total is O(n log n). Merge sort is the standard example. When it recurses on only one half, as binary search does, the total is O(log n).

Recursion uses space. Every call waits on the call stack until it returns, so recursion to depth d uses O(d) space even when the code allocates nothing. Tree DFS on a skewed tree of n nodes therefore uses O(n) space, not O(log n).

Mistakes that change the complexity

These are the errors interviewers catch most often when a candidate states a complexity that the code does not have.

Searching a list inside a loop. Checking whether a value is in a list costs O(n), so doing it inside a loop makes the whole solution O(n^2). A set or hash map makes the same check O(1) on average.

Building a string piece by piece. Adding to a string in a loop can copy the whole string at each step, which costs O(n^2) overall. Java always copies, and CPython only sometimes avoids the copy. Collect the pieces in a list and join them once.

Slicing and copying. A slice of an array or a string creates a copy of length k, which costs O(k). Passing slices into a recursive function adds that cost at every call.

Sorting inside a loop. A sort is O(n log n) every time it runs. Sorting once before the loop, or keeping a heap, is usually the intended solution.

Forgetting the output. When a problem asks for all subsets or all permutations, the output alone is exponential in size. No algorithm can be faster than the time it takes to write its output.

How to state complexity in an interview

Name the variables first. If the input is a grid, say m and n; if there are two lists, say n and m; if the problem has a k, keep it in the answer. An answer of O(n log k) is more precise than O(n log n), and interviewers notice the difference.

Then give time and space in one sentence each, and point to the line that sets each one. For example: "The time is O(n log k), because each of the n elements costs one heap operation, and the heap never holds more than k items. The extra space is O(k) for the heap."

Finally, say whether the bound is average or worst case when they differ. A solution built on a hash map is O(n) on average, and saying so shows you know when the worst case applies.

Learn complexity analysis properly: Grokking Algorithm Complexity and Big-O teaches how to derive the bound for loops, recursion, and data structures step by step. To apply it pattern by pattern, Grokking the Coding Interview covers all 41 patterns for $79 once.

The takeaway

Big O is a tool in two places in an interview. Read the input limit first, and it tells you which complexity, and therefore which patterns, the intended solution can have. After you code, state time and space with named variables and point to the line that causes each term. The tables above cover the classes, the limits, the data structure operations, and the typical cost of every common pattern.

FAQs

What is Big O notation in simple terms? Big O notation describes how the running time or memory of an algorithm grows as the input grows. It ignores constant factors and keeps only the fastest-growing term, so 3n + 20 steps is written O(n).

What is the difference between time complexity and space complexity? Time complexity counts the steps an algorithm takes as the input grows. Space complexity counts the extra memory it uses beyond the input, including the recursion stack. Interviewers expect both in every answer.

Which is faster, O(n log n) or O(n)? O(n) grows more slowly, so it is faster for large inputs. The difference is small in practice, since log n is only about 20 for a million items, which is why sorting first is often acceptable.

What does O(log n) mean? It means the problem size is divided by a constant, usually two, at each step. Binary search on a million sorted items needs only about 20 steps, because a million halves to one in about 20 steps.

What is amortized time complexity? Amortized time is the average cost per operation over a long sequence of operations. Appending to a dynamic array occasionally costs O(n) to resize, but the average over many appends is O(1).

How do I find the time complexity of a recursive function? Without memoization, estimate the branches raised to the depth. With memoization or dynamic programming, multiply the number of distinct states by the work done in each state. Add the recursion depth to the space complexity.

What input size does an O(n^2) solution handle? About 5,000 to 10,000 elements within a typical one- or two-second limit. If the constraints allow 100,000 or more, the intended solution is almost always O(n log n) or O(n).

Grokking the Coding Interview
One-Stop Portal For Coding Interviews.
Follow us:
Copyright © 2025 Coding Interview All rights reserved.