Vasu Patel logoVasu Patel
← Python DSA — Course
All chapters in this track
  1. 011. Complexity Analysis
  2. 022. Arrays & Strings
  3. 033. Hashing
  4. 044. Stacks & Queues
  5. 055. Linked Lists
  6. 066. Binary Search
  7. 077. Sorting
  8. 088. Recursion & Backtracking
  9. 099. Trees
  10. 1010. Heaps
  11. 1111. Graphs
  12. 1212. Dynamic Programming
  13. 1313. Tries
  14. 1414. Advanced Structures
  15. 15Appendix: CP Quick Reference

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, 10810^8 simple operations ≈ 1 second; use this to choose the right algorithm tier.

Big-O Cheat Sheet

ComplexityNameMax nn in 1sExample
O(1)O(1)ConstantAnyHash lookup
O(log⁡n)O(\log n)Logarithmic101810^{18}Binary search
O(n)O(n)Linear10810^8Single loop
O(nlog⁡n)O(n \log n)Linearithmic10610^6Merge sort
O(n2)O(n^2)Quadratic10410^4Nested loop
O(n3)O(n^3)Cubic5005003-loop DP
O(2n)O(2^n)Exponential20–2520\text{–}25Subset enumeration
O(n!)O(n!)Factorial1212Permutations

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.append is O(1)O(1) amortized: occasional O(n)O(n) resize is spread over nn appends.
  • dict inserts are O(1)O(1) amortized but can degrade with poor hash functions (rare in Python).

Space Complexity

  • Always track auxiliary space separately from input space.
  • Recursion depth = O(n)O(n) stack space for DFS on a skewed tree.