⚡ Complexity Cheatsheet
Quick Reference
Dùng file này như một “cheat sheet” trong interview prep. In ra hoặc pin lên màn hình. ← Roadmap-FAANG
Constraint → Algorithm Map
| Input Size | Max Complexity | Algorithms |
|---|---|---|
| Permutations, brute force | ||
| Bitmask DP with transitions | ||
| Subset enumeration, Bitmask DP | ||
| Floyd-Warshall, 3D DP | ||
| Matrix chain multiplication DP | ||
| Bubble/Insertion sort, DP | ||
| String matching naive, 2D grid BFS | ||
| Merge sort, Heap, Segment Tree, Dijkstra | ||
| Two pointers, Sliding window, Linear sort | ||
| Binary search, Fast exponentiation | ||
| Binary search on answer + check |
Data Structure Complexities
Array / Dynamic Array
| Operation | Average | Worst |
|---|---|---|
| Access | ||
| Search | ||
| Insert (end) | amortized | |
| Insert (middle) | ||
| Delete |
Linked List
| Operation | Average | Notes |
|---|---|---|
| Access | No random access | |
| Search | ||
| Insert (head) | ||
| Insert (tail with tail pointer) | ||
| Insert (middle — after finding node) | Finding is |
Hash Table
| Operation | Average | Worst (hash collision) |
|---|---|---|
| Search | ||
| Insert | ||
| Delete |
Hash Map trong JS/TS
Map<K,V>vàSet<T>đều average. Tránh dùng plain object{}cho numeric keys vì key order behavior khác.
Binary Search Tree (Balanced — AVL/Red-Black)
| Operation | Average | Worst |
|---|---|---|
| Search | ||
| Insert | ||
| Delete |
Heap (Binary Heap)
| Operation | Complexity |
|---|---|
| Build heap | |
| Insert | |
| Get min/max | |
| Extract min/max | |
| Decrease key |
Graph
| Algorithm | Time | Space | Use Case |
|---|---|---|---|
| BFS | Shortest path (unweighted) | ||
| DFS | Cycle detection, topo sort | ||
| Dijkstra | Shortest path (non-negative weights) | ||
| Bellman-Ford | Shortest path (negative weights) | ||
| Floyd-Warshall | All-pairs shortest path | ||
| Prim’s MST | Minimum spanning tree | ||
| Kruskal’s MST | Minimum spanning tree |
Sorting
| Algorithm | Best | Average | Worst | Space | Stable? |
|---|---|---|---|---|---|
| Merge Sort | ✅ | ||||
| Quick Sort | ❌ | ||||
| Heap Sort | ❌ | ||||
| Tim Sort (JS default) | ✅ | ||||
| Counting Sort | ✅ | ||||
| Radix Sort | ✅ |
Recursion & DP Space Complexity
| Type | Space |
|---|---|
| Recursion depth | — thường là hoặc |
| Memoization (top-down DP) | + call stack |
| Tabulation (bottom-up DP) | — no call stack overhead |
| Space-optimized DP (1D rolling) |
String Algorithms
| Algorithm | Time | Use Case |
|---|---|---|
| Naive pattern match | Simple, small inputs | |
| KMP | Pattern matching | |
| Rabin-Karp (Rolling Hash) | avg | Multiple pattern search |
| Z-algorithm | Pattern matching | |
| Trie insert/search | Prefix search, = word length | |
| Suffix Array | build | Advanced string problems |
Master Theorem (Divide & Conquer)
Với recurrence:
| Condition | Result |
|---|---|
Common examples:
- Merge Sort: → →
- Binary Search: →