Skip to content

Instantly share code, notes, and snippets.

@jcoding09
Last active June 28, 2026 17:40
Show Gist options
  • Select an option

  • Save jcoding09/1880f5b6999f61dd3221ba4785713733 to your computer and use it in GitHub Desktop.

Select an option

Save jcoding09/1880f5b6999f61dd3221ba4785713733 to your computer and use it in GitHub Desktop.

Dynamic Programming β€” Complete Category Guide

Core Categories (from video)

  1. 1-D DP β€” Linear state problems (Fibonacci, House Robber, Climbing Stairs)
  2. Hard Problems on 1-D DP β€” Advanced single-dimension state transitions
  3. 2-D DP β€” Grid/matrix problems, two-variable states
  4. 3-D / 4-D DP β€” Multi-dimensional state spaces
  5. Subarray / Mix DP β€” DP on subarrays (MCM, Burst Balloons)
  6. Partition DP β€” Splitting arrays/strings optimally
  7. Partition DP + Optimization β€” With divide & conquer or other speedups
  8. Digit DP β€” Counting numbers with digit constraints (along with optimization)
  9. Knapsack DP β€” 0/1, Unbounded, Bounded knapsack
  10. Knapsack DP + Variations & Optimizations β€” Subset sum, target sum variants
  11. String DP β€” LCS, Edit Distance, and all variations
  12. Special Optimizations on DP β€” Hashing / Math / Convex-Hull Trick / Observations / Segment Tree / Stack Optimization
  13. LIS DP β€” Longest Increasing Subsequence and variants (LDS, LIDS, etc.)
  14. Miscellaneous DP β€” Problems that don't fit neatly elsewhere
  15. Kadane DP β€” Prefix / Suffix / Hashing + DP hybrids
  16. Tiling DP + Broken DP β€” Domino tiling, broken tile problems

Additional Categories (recommended additions)

  1. Bitmask DP β€” State compression using bitmasks (TSP, assignment problems)
  2. Tree DP β€” DP on trees (rerooting technique, subtree states)
  3. DP on Graphs / DAG DP β€” Longest path in DAG, topological order DP
  4. Interval DP β€” Palindrome partitioning, matrix chain, optimal BST
  5. Probability / Expected Value DP β€” Games, dice, random walks
  6. DP + Data Structures β€” BIT/Fenwick, Segment Tree augmented DP
  7. SOS DP (Sum over Subsets) β€” Subset enumeration with bitmask
  8. Profile DP β€” Row-by-row state compression (broken profile)
  9. DP on Strings with Automata β€” Aho-Corasick + DP, regex matching

Quick Reference by Difficulty

Level Categories
Beginner 1-D DP, 2-D DP, Knapsack, String DP
Intermediate Partition DP, LIS, Interval DP, Tree DP, Bitmask DP
Advanced Digit DP, SOS DP, Profile DP, Convex Hull Trick, Automata DP
Expert 3-D/4-D DP, Stack Optimization, DP + Segment Tree, Probability DP

🟒 Easy

  1. 1-D DP

    • Linear state problems (Fibonacci, House Robber, Climbing Stairs)
  2. 2-D DP

    • Grid/matrix problems, two-variable states
  3. Knapsack DP

    • 0/1, Unbounded, Bounded knapsack
  4. String DP

    • LCS, Edit Distance, and all variations
  5. LIS DP

    • Longest Increasing Subsequence and variants (LDS, LIDS)
  6. Kadane DP

    • Prefix / Suffix / Hashing + DP hybrids

🟑 Medium

  1. Hard Problems on 1-D DP

    • Advanced single-dimension state transitions
  2. Subarray / Mix DP

    • DP on subarrays (MCM, Burst Balloons)
  3. Partition DP

    • Splitting arrays/strings optimally
  4. Knapsack DP + Variations & Optimizations

    • Subset sum, target sum variants
  5. Interval DP

    • Palindrome partitioning, matrix chain, optimal BST
  6. Tiling DP + Broken DP

    • Domino tiling, broken tile problems
  7. Tree DP

    • DP on trees (rerooting technique, subtree states)
  8. Miscellaneous DP

    • Problems that don't fit neatly elsewhere

πŸ”΄ Hard

  1. 3-D / 4-D DP

    • Multi-dimensional state spaces
  2. Partition DP + Optimization

    • With divide & conquer or other speedups
  3. Digit DP

    • Counting numbers with digit constraints (along with optimization)
  4. Bitmask DP

    • State compression using bitmasks (TSP, assignment problems)
  5. DP on Graphs / DAG DP

    • Longest path in DAG, topological order DP
  6. Probability / Expected Value DP

    • Games, dice, random walks
  7. SOS DP (Sum over Subsets)

    • Subset enumeration with bitmask

⚫ Very Hard

  1. Special Optimizations on DP

    • Hashing / Math / Convex-Hull Trick / Observations / Segment Tree / Stack Optimization
  2. DP + Data Structures

    • BIT/Fenwick, Segment Tree augmented DP
  3. Profile DP

    • Row-by-row state compression (broken profile)
  4. DP on Strings with Automata

    • Aho-Corasick + DP, regex matching

Competitive Programming Roadmap (C++ Focus)

From Absolute Beginner β†’ Codeforces Div.2 D/E Level


Tier 1 β€” CP Foundations & Programming Basics 🟒

1.1 C++ Core Constructs

  • I/O: cin/cout, fast I/O:
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  • Use \n instead of endl (avoids buffer flush)
  • Control Flow: if/else/switch, for/while/do-while, range-based loops
  • Functions: Pass-by-value vs pass-by-reference (&), global vs local scope

1.2 Data Types & Overflow

  • Types: int, long long, float, double, char, string, bool, __int128
  • Bounds: int β‰ˆ Β±2Γ—10⁹ | long long β‰ˆ Β±9Γ—10¹⁸
  • Overflow fix: 1LL * a * b
  • Modulo rules:
    • (A+B)%M = ((A%M)+(B%M))%M
    • (AΓ—B)%M = ((A%M)Γ—(B%M))%M
    • (A-B)%M = ((A%M)-(B%M)+M)%M

1.3 Complexity Analysis

  • Big O / Ξ© / Θ β€” worst, best, average cases
  • Golden Rule: ~10⁸ ops/sec on judge
Constraint Expected Complexity
N ≀ 10 O(N!) or O(2^N Β· NΒ²)
N ≀ 20 O(2^N)
N ≀ 500 O(NΒ³)
N ≀ 5000 O(NΒ²)
N ≀ 2Γ—10⁡ O(N log N)
N ≀ 10⁷ O(N)
Large N O(log N) or O(1)
  • Space: 256–512MB typical limit | int array of 10⁷ β‰ˆ 40MB

1.4 STL Basics

  • Containers: vector, pair, tuple
  • Iterators: begin/end, rbegin/rend
  • Algorithms: sort, reverse, max_element, min_element

Tier 2 β€” Linear DS & Optimization Techniques 🟒

2.1 Arrays

  • 1D/2D arrays, cache efficiency, contiguous memory
  • Grid traversal (4-directional / 8-directional)

2.2 Strings

  • substr(), find(), stringstream, to_string(), stoi()
  • char arrays vs std::string β€” null terminators, layout

2.3 Prefix Sums & Difference Arrays

  • 1D prefix sum β†’ O(1) range queries
  • 2D prefix sum β†’ O(1) submatrix queries
  • Difference array β†’ O(1) range updates + single prefix reconstruct
  • Coordinate compression β†’ map sparse values to dense indices

2.4 Two Pointers

  • Converging (pair sum, palindrome check)
  • Independent (merge sorted arrays, fast/slow pointer)

2.5 Sliding Window

  • Fixed size β†’ rolling max/sum of size K
  • Variable size β†’ longest subarray satisfying constraint

Tier 3 β€” Algorithm Paradigms Phase 1 🟑

3.1 Sorting

  • Merge Sort / Quick Sort internals (Divide & Conquer)
  • Custom comparators, lambda sort, operator < overloading
  • Strict Weak Ordering rules

3.2 Binary Search

  • lower_bound (β‰₯ target), upper_bound (> target), binary_search
  • Binary Search on Answer β€” monotonic predicate (T...T F...F)
  • Floating point BS: use 100 fixed iterations

3.3 Bit Manipulation

Operation Code
Check bit i mask & (1 << i)
Set bit i mask | (1 << i)
Clear bit i mask & ~(1 << i)
Toggle bit i mask ^ (1 << i)
Lowest set bit mask & (-mask)
  • GCC builtins: __builtin_popcount, __builtin_clz, __builtin_ctz
  • Bitmasks for subset representation (N ≀ 30)

3.4 Greedy Algorithms

  • Locally optimal β†’ globally optimal
  • Activity selection, Fractional Knapsack, Huffman Coding
  • Proof: Exchange argument / Staying ahead

3.5 Number Theory ⭐ (Critical Addition)

  • Sieve of Eratosthenes β€” all primes up to N in O(N log log N)
  • GCD / LCM β€” __gcd(), Euclidean algorithm
  • Modular Exponentiation β€” fast power in O(log N)
  long long power(long long base, long long exp, long long mod) {
      long long result = 1;
      while (exp > 0) {
          if (exp & 1) result = result * base % mod;
          base = base * base % mod;
          exp >>= 1;
      }
      return result;
  }
  • Modular Inverse β€” Fermat's little theorem: a^(M-2) % M (M prime)
  • Prime Factorization β€” trial division, smallest prime factor sieve
  • Euler's Totient Function Ο†(N)
  • Chinese Remainder Theorem (CRT) β€” basic application

Tier 4 β€” Recursion & Intermediate DS 🟑

4.1 Recursion

  • Base cases, call stack depth, recurrence relations
  • Execution tree visualization, stack overflow awareness

4.2 Stack & Queue

  • Stack (std::stack): Balanced parentheses, expression parsing
  • Monotonic Stack: NGE / PSE queries in O(N)
  • Queue (std::queue): BFS backbone, FIFO
  • Deque (std::deque): O(1) push/pop both ends β†’ Sliding window max

4.3 Hashing & Associative Containers

  • set / map / multiset β†’ O(log N), Red-Black tree backed
  • unordered_map / unordered_set β†’ O(1) avg, ⚠️ anti-hash vulnerable
  • Fix with custom hash:
  struct custom_hash {
      static uint64_t splitmix64(uint64_t x) {
          x += 0x9e3779b97f4a7c15;
          x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
          x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
          return x ^ (x >> 31);
      }
      size_t operator()(uint64_t x) const {
          static const uint64_t FIXED_RANDOM =
              chrono::steady_clock::now().time_since_epoch().count();
          return splitmix64(x + FIXED_RANDOM);
      }
  };
  // unordered_map<long long, int, custom_hash> safe_map;

4.4 Backtracking

  • Generate subsets, permutations, power set
  • N-Queens, Sudoku Solver
  • Prune dead-end branches early

Tier 5 β€” Advanced DS: Segment Tree, BIT & DSU ⭐ πŸ”΄

(New dedicated tier β€” critical before advanced DP)

5.1 Fenwick Tree / Binary Indexed Tree (BIT)

  • Point update + prefix sum query in O(log N)
  • 2D BIT for matrix range queries
  • Applications: Inversion count, order statistics

5.2 Segment Tree

  • Range query + point update in O(log N)
  • Lazy Propagation β€” range update + range query in O(log N)
  • Applications: Range min/max/sum, range assignment
  • Merge sort tree variant for frequency queries

5.3 Sparse Table

  • O(1) range min/max queries (static arrays, no updates)
  • Build in O(N log N), query in O(1) β€” ideal for RMQ

5.4 Disjoint Set Union (DSU) / Union-Find ⭐

  • find() with path compression
  • union() with union by rank/size
  • O(Ξ±(N)) β‰ˆ O(1) amortized per operation
  • Applications: Connected components, Kruskal's MST, cycle detection

Tier 6 β€” Graph Theory & Tree Algorithms πŸ”΄

6.1 Graph Representations

  • Adjacency Matrix β†’ O(1) lookup, O(VΒ²) space
  • Adjacency List β†’ O(V+E) space (always prefer this)
  • Edge List β†’ for MST algorithms

6.2 BFS

  • Shortest path in unweighted graphs, connected components
  • Bipartite graph detection
  • 0-1 BFS β€” deque, weights ∈ {0,1}, O(V+E)

6.3 DFS

  • Cycle detection (directed + undirected)
  • Connected components, Flood Fill
  • Euler Tour β€” entry/exit timestamps for subtree queries

6.4 Shortest Path Algorithms ⭐ (Critical Addition)

Algorithm Weights Complexity Use Case
BFS Unweighted O(V+E) Equal edge weights
Dijkstra Non-negative O((V+E) log V) Standard SSSP
Bellman-Ford Any (neg OK) O(VΓ—E) Negative edges
Floyd-Warshall Any O(VΒ³) All pairs SP
0-1 BFS {0,1} only O(V+E) Binary weights

6.5 Topological Sort ⭐

  • Kahn's Algorithm (BFS) β€” in-degree tracking
  • DFS-based β€” post-order reversal
  • Applications: Task scheduling, DAG DP ordering

6.6 Minimum Spanning Tree (MST)

  • Kruskal's β€” sort edges + DSU, O(E log E)
  • Prim's β€” priority queue, O((V+E) log V)

6.7 Tree Fundamentals

  • Connected acyclic graph, exactly V-1 edges
  • Pre/In/Post-order traversals
  • DFS: depth, height, subtree sizes
  • Tree Diameter β€” 2Γ— DFS or DP
  • LCA (Lowest Common Ancestor) β€” binary lifting, O(N log N) build, O(log N) query

6.8 Divide & Conquer on Problems

  • Inversion count via Merge Sort
  • Closest pair of points

Tier 7 β€” Dynamic Programming Mastery πŸ”΄βš«

7.1 Core DP Concepts

  • Prerequisites: Overlapping subproblems + Optimal substructure
  • Top-Down: Recursion + memoization (cache array)
  • Bottom-Up: Iterative tabulation, no recursion overhead
  • Always define: State β†’ Transition β†’ Base Case

7.2 1-D DP 🟒

  • Fibonacci variants, climbing stairs
  • House Robber (non-adjacent selection)
  • Max subarray (Kadane's Algorithm)
  • Jump Game variants

7.3 2-D DP 🟒

  • Grid path counting with obstacles
  • Minimum path sum in grid
  • Unique paths with constraints

7.4 Knapsack DP 🟑

  • 0/1 Knapsack β€” take or leave, no reuse
  • Unbounded Knapsack β€” infinite item reuse
  • Bounded Knapsack β€” limited item count
  • Subset Sum β€” exact target reachability
  • Partition DP β€” equal subset split

7.5 String DP 🟑

  • LCS β€” Longest Common Subsequence (2D table)
  • Edit Distance β€” insert / delete / replace
  • LPS β€” Longest Palindromic Subsequence
  • Wildcard / Regex Matching
  • Distinct Subsequences

7.6 LIS DP 🟑

  • Standard LIS β€” O(NΒ²)
  • Optimized LIS β€” O(N log N) with lower_bound
  • Variants: LDS, LIDS, LIS count, print LIS
  • Russian Doll Envelopes (2D LIS)

7.7 Interval DP πŸ”΄ ⭐ (Critical Addition)

  • Matrix Chain Multiplication
  • Burst Balloons
  • Palindrome Partitioning
  • Optimal BST
  • Template:
for length 2 β†’ N:
    for every interval [i, j] of that length:
        for every split point k in [i, j]:
            dp[i][j] = optimal(dp[i][k] + dp[k+1][j] + cost)

7.8 Partition DP πŸ”΄

  • Rod Cutting
  • Palindrome min-cut partitioning
  • Egg Drop Problem
  • Splitting array into K parts optimally

7.9 Digit DP πŸ”΄

  • Count numbers in [L, R] satisfying digit constraints
  • States: (index, tight, started, criteria)
  • Applications: Count numbers with digit sum = K, no consecutive same digits

7.10 Bitmask DP πŸ”΄

  • Subsets as DP states (N ≀ 20)
  • TSP β€” O(2^N Β· NΒ²)
  • Assignment Problem
  • SOS DP (Sum over Subsets) β€” O(N Β· 2^N)
  for (int mask = 0; mask < (1 << n); mask++)
      for (int i = 0; i < n; i++)
          if (mask & (1 << i))
              dp[mask] += dp[mask ^ (1 << i)];

7.11 Tree DP πŸ”΄

  • dp[u][state] β€” subtree subproblems
  • Max Independent Set on Tree
  • Subtree weight optimization
  • Tree Diameter via DP
  • Rerooting Technique β€” O(N) all-root DP

7.12 Kadane DP / Prefix-Suffix DP 🟑

  • Maximum subarray sum (Kadane's)
  • Maximum subarray product
  • Prefix + Suffix combination problems
  • Hashing + DP hybrids

7.13 3-D / 4-D DP πŸ”΄

  • Multiple simultaneous constraints
  • Cherry Pickup (two paths simultaneously)
  • DP with 3+ state variables

7.14 Special Optimizations on DP ⚫

  • Convex Hull Trick (CHT) β€” O(N) line optimization
  • Li Chao Tree β€” dynamic CHT with arbitrary queries
  • Divide & Conquer DP β€” opt monotonicity β†’ O(N log N)
  • Knuth's Optimization β€” interval DP β†’ O(NΒ²) from O(NΒ³)
  • Stack Optimization β€” monotonic stack on DP transitions
  • Segment Tree / BIT on DP β€” range optimal transitions

7.15 Miscellaneous DP ⚫

  • Profile DP β€” broken profile, row-by-row state compression
  • Tiling DP + Broken DP β€” domino/tromino tiling
  • Probability / Expected Value DP β€” games, dice, random walks
  • DP on DAG β€” longest/shortest path via topological order
  • LIS DP on Strings with Automata β€” Aho-Corasick + DP

7.16 Space Optimization 🟑

  • Rolling array β†’ reduce NΓ—W to 2Γ—W or 1Γ—W
  • Only store previous row/layer when current depends on it
  • Recognize traversal direction matters (forward vs reverse)

Quick Reference β€” DP Category by Difficulty

Difficulty Categories
🟒 Easy 1-D DP, 2-D DP, Kadane, Basic Knapsack, Basic String DP
🟑 Medium LIS, Full Knapsack, Full String DP, Partition DP, Tree DP basics
πŸ”΄ Hard Interval DP, Digit DP, Bitmask DP, 3D/4D DP, Rerooting
⚫ Very Hard CHT, Li Chao, D&C DP, Knuth's Opt, Profile DP, Automata DP

Problem Count Targets per Tier

Tier Target Problems Goal
Tier 1–2 30–50 Build speed & fluency
Tier 3–4 50–80 Pattern recognition
Tier 5–6 60–100 Graph confidence
Tier 7 DP 100–150 Master all DP types
Total ~300 Div.2 D/E ready
#include <bits/stdc++.h>
using namespace std;
// ───── Type Aliases ─────
// Rule of thumb: only alias a type if ALL 3 are true:
// 1. You use it in >30% of problems
// 2. You use it without modification (no custom comparator/hash/size)
// 3. The original name is long enough to be annoying
// e.g. vector<vector<int>> β†’ all three βœ“ β†’ aliased as vvi
// vector<vector<vector<int>>> β†’ fails rule 1 & 2 β†’ skipped
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vector<int>>;
using vvl = vector<vector<ll>>;
using vpii = vector<pii>;
using vpll = vector<pll>;
using si = set<int>;
using mii = map<int, int>;
using mll = map<ll, ll>;
using msi = map<string, int>;
using str = string;
// ───── Macros ─────
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define sz(x) (int)(x).size()
#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define per(i, a, b) for (int i = (b) - 1; i >= (a); --i)
// ───── Constants ─────
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int MOD = 1e9 + 7;
const double PI = acos(-1.0);
// ───── Debug (disabled on judge) ─────
#ifdef LOCAL
#define dbg(x) cerr << #x << " = " << (x) << "\n"
#else
#define dbg(x)
#endif
// ───── Fast I/O ─────
void setIO(const string& name = "") {
ios::sync_with_stdio(false);
cin.tie(nullptr);
if (!name.empty()) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
// ───── Utility ─────
template<typename T> void chmin(T& a, const T& b) { if (b < a) a = b; }
template<typename T> void chmax(T& a, const T& b) { if (b > a) a = b; }
ll power(ll base, ll exp, ll mod = MOD) {
ll result = 1;
base %= mod;
while (exp > 0) {
if (exp & 1) result = result * base % mod;
base = base * base % mod;
exp >>= 1;
}
return result;
}
// ═══════════════════════════════════════
void solve() {
// ── your solution here ──
}
// ═══════════════════════════════════════
int main() {
setIO(); // pass a filename string for file I/O, e.g. setIO("problem")
int t = 1;
cin >> t; // remove this line if there's only one test case
while (t--) solve();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment