Cohort 4Register

PART 7 · PRACTICE, PREP FLOW AND REVISION

Complexity cheat sheet

FreeLesson 76 of 78

Every cost you will be asked to state, on one page. If you can fill this table from memory, the complexity questions are free marks.

Data structures

StructureAccessSearchInsertDeleteSpaceBest for
list (array)O(1)O(n)O(1) end, O(n) frontO(1) end, O(n) frontO(n)Ordered data, indexing
dict / setO(1)*O(1)*O(1)*O(1)*O(n)Lookups, counting, dedupe
dequeO(1) endsO(n)O(1) both endsO(1) both endsO(n)Queues, windows, BFS
heap (heapq)O(1) minO(n)O(log n)O(log n) minO(n)Top-k, scheduling, merge k
sorted list + bisectO(1)O(log n)O(n)O(n)O(n)Static sorted lookups
balanced BST / B-treeO(log n)O(log n)O(log n)O(log n)O(n)Database indexes
linked listO(n)O(n)O(1) at a nodeO(1) at a nodeO(n)Rare in Python

* average case. Worst case O(n) with heavy hash collisions, which you can mention but rarely need to worry about.

Algorithms

AlgorithmTimeSpacePage
Binary searchO(log n)O(1)50
Sorting (Timsort, merge sort)O(n log n)O(n)51
Counting sortO(n + k)O(k)51
Two pointers, sliding windowO(n)O(1) to O(k)45, 47
Prefix sumsO(n) build, O(1) queryO(n)43, 46
BFS / DFS on V nodes, E edgesO(V + E)O(V)53, 54
Topological sort (Kahn)O(V + E)O(V)54
Top-k with a heapO(n log k)O(k)55, 59
Merge k sorted streamsO(n log k)O(k)61
Subsets / permutationsO(2^n) / O(n!)O(n) depth52
DP over one dimensionO(n x choices)O(n), often O(1)56
Hash join of n and m rowsO(n + m)O(smaller side)65
Mistake when stating complexitySay this instead
"It is O(n)" for a loop that calls x in some_listO(n x m): the in on a list is its own loop (page 44)
Forgetting the sort you addedO(n log n) overall, even if the rest is O(n)
Calling recursion O(1) spaceO(depth) for the call stack
O(n) for building a string with += in a loopUp to O(n²) copying; join is O(n)
Ignoring the output sizeListing all subsets is at least O(2^n): the answer itself is that big

Practice before you move on

  1. Cover the complexity column and fill it in from memory.
  2. Pick two rows of the table and write a snippet that times them.