All chapters in this track
Chapter 1 of 15
1. Complexity Analysis
Key Insight
Big-O describes how runtime or memory scales as input grows — not absolute speed. Always analyze the worst case unless told otherwise. In CP, simple operations ≈ 1 second; use this to choose the right algorithm tier.
Big-O Cheat Sheet
| Complexity | Name | Max in 1s | Example |
|---|---|---|---|
| Constant | Any | Hash lookup | |
| Logarithmic | Binary search | ||
| Linear | Single loop | ||
| Linearithmic | Merge sort | ||
| Quadratic | Nested loop | ||
| Cubic | 3-loop DP | ||
| Exponential | Subset enumeration | ||
| Factorial | Permutations |
Python-Specific Gotchas
# list.append / list.pop(-1) → O(1) amortized
# list.insert(0, x) / list.pop(0) → O(n) — use collections.deque instead
# dict / set lookup, insert, delete → O(1) average, O(n) worst (hash collision)
# sorted() / list.sort() → O(n log n) — Timsort
# "".join(list_of_str) → O(n); repeated += on str → O(n²) — always use join
# in operator on list → O(n); on set/dict → O(1)
import sys
# Recursion limit — increase for deep DFS
sys.setrecursionlimit(300_000)
# Fast I/O for CP
input = sys.stdin.readline
Amortized Analysis
list.appendis amortized: occasional resize is spread over appends.dictinserts are amortized but can degrade with poor hash functions (rare in Python).
Space Complexity
- Always track auxiliary space separately from input space.
- Recursion depth = stack space for DFS on a skewed tree.