Back to Notes

Big O & Complexity

Big O Categories

Big-ONameSpeedExample
O(1)ConstantBestArray index lookup
O(log n)LogarithmicGreatBinary search
O(n)LinearGoodSingle loop through array
O(n log n)LinearithmicOkayMerge sort, Quick sort (avg)
O(n²)QuadraticSlowNested loops, Bubble sort
O(n³)CubicSlowerTriple nested loops
O(2ⁿ)ExponentialHorribleBrute-force subsets
O(n!)FactorialWorstGenerating all permutations

Common Data Structure Operations

Data StructureAccessSearchInsertDelete
ArrayO(1)O(n)O(n)O(n)
Stack / QueueO(n)O(n)O(1)O(1)
Linked ListO(n)O(n)O(1)O(1)
Hash MapO(1) avgO(1) avgO(1) avgO(1) avg
BST (balanced)O(log n)O(log n)O(log n)O(log n)
HeapO(1) peekO(n)O(log n)O(log n)

Common Sorting Complexities

AlgorithmBestAverageWorstSpaceStable?
Bubble SortO(n)O(n²)O(n²)O(1)Yes
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
Quick SortO(n log n)O(n log n)O(n²)O(log n)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Python sorted() (Timsort)O(n)O(n log n)O(n log n)O(n)Yes

P vs NP

  • P — Problems that can be solved in polynomial time (e.g., sorting, binary search)
  • NP — Problems whose solutions can be verified in polynomial time, but not necessarily solved fast (e.g., Sudoku, Travelling Salesman)
  • P ⊆ NP — Every problem solvable in polynomial time can also be verified in polynomial time
  • P = NP? — The biggest unsolved question in computer science

For interviews: just know that NP-hard problems have no known efficient solution — you typically use approximations or heuristics.


Space Complexity Notes

  • O(1) — In-place (only a few variables, no extra data structures)
  • O(log n) — Recursion stack depth for divide-and-conquer on balanced input
  • O(n) — Storing a copy of the input, or recursion on a linear structure
  • O(n²) — Storing a 2D grid/DP table