DP
Interval DP
- Burst Balloons~2100LC 312★ core
Hint
Choose the balloon k that bursts last in (l, r). At that point its neighbours are l-1 and r+1, so dp[l][r] = max over k of dp[l][k-1] + dp[k+1][r] + a[l-1]·a[k]·a[r+1]. - Minimum Score Triangulation of Polygon~1900LC 1039
Hint
Edge (i, j) belongs to exactly one triangle (i, k, j). dp[i][j] = min over k of dp[i][k] + dp[k][j] + v[i]v[k]v[j]. - Minimum Cost to Cut a Stick~2100LC 1547★ core
Hint
Add 0 and n to the cuts and sort them. Run the DP over cut indices. The cost of a segment is cuts[j] - cuts[i], whichever cut happens first. - Strange Printer~2200LC 664★ core
Hint
dp[l][r] = dp[l+1][r] + 1, or for any k with s[k] == s[l], merge s[l]'s stroke into s[k]'s: dp[l+1][k-1] + dp[k][r]. - Clear the String~2000CF 1132F
Hint
Same structure as Strange Printer: delete s[l] alone, or save it for the same deletion as a later equal character k. - Zuma~1900CF 607B
Hint
dp[l][r] = min(1 + dp[l+1][r], 1 + dp[l+2][r] if c[l] == c[l+1], dp[l+1][k-1] + dp[k+1][r] for c[k] == c[l]). Gem l is removed together with gem k, wrapped around the middle. - Minimum Cost to Merge Stones~2400LC 1000
Hint
If (n-1) % (K-1) ≠ 0 the answer is -1. dp[l][r] is the cost of merging the range down as far as possible. Split at m in steps of K-1, and add the range sum when (r-l) % (K-1) == 0. - Remove Boxes~2700LC 546
Hint
Two dimensions aren't enough. Add a third: dp[l][r][k], where k boxes equal to box[l] are attached on the left. Either remove them now, or join them with a later equal box.
Bitmask DP & SOS
- Shortest Path Visiting All Nodes~2000LC 847★ core
Hint
Multi-source BFS over (node, visited mask), starting from every node with mask = 1<<node. - Minimum XOR Sum of Two Arrays~2000LC 1879
Hint
dp[mask] means nums2 elements in mask are used. The next nums1 index is popcount(mask). - Smallest Sufficient Team~2200LC 1125★ core
Hint
Iterate over people; dp[mask | skills[p]] = min(dp[mask] + 1). Store a parent pointer instead of copying lists. - Find the Shortest Superstring~2400LC 943
Hint
Precompute pairwise overlaps. Then it's TSP: dp[mask][last] = max total overlap. Reconstruct the string from parent pointers. - Parallel Courses II~2600LC 1494★ core
Hint
Greedy topological order is wrong. dp[mask] = minimum semesters. avail = courses whose prerequisites are all in mask; try every submask of avail with size ≤ k (or all of avail if it fits). - Maximum Students Taking Exam~2400LC 1349
Hint
Row-by-row mask DP. cur must avoid broken seats and have no adjacent bits; it's compatible with prev if (cur<<1 & prev) and (cur>>1 & prev) are both 0. - Maximum AND Sum of Array~2400LC 2172
Hint
Each slot holds 2 numbers, so use 2·numSlots bits. The number being placed is popcount(mask). - Compatible Numbers~2200CF 165E
Hint
You need some b with a & b = 0, so b ⊆ ~a. SOS DP: best[mask] = any element that is a submask of mask.
Digit DP
- Numbers At Most N Given Digit Set~1900LC 902
Hint
Shorter lengths contribute d^len for free. Then walk n's digits while tight. - Number of Digit One~2000LC 233★ core
Hint
Per position: split into high / cur / low and count how often this digit is 1. This is the contribution form of a digit DP. - Count Special Integers~2100LC 2376★ core
Hint
State (pos, used-digit mask, tight, started). Zeros before the number starts don't go into the mask. - Numbers With Repeated Digits~2200LC 1012
Hint
Count the complement: n minus the numbers ≤ n with all distinct digits. - Count of Integers~2350LC 2719★ core
Hint
dp(pos, digit sum, tight), with the sum capped at max_sum. The answer is f(num2) - f(num1) + [num1 itself is valid]. - ~1900
Tree DP & rerooting
- Choosing Capital for Treeland~1700CF 219D
Hint
Store each edge in both directions: cost 0 along the original direction, 1 against it. Count the cost for root 0, then moving the root across an edge flips that edge's contribution. - Maximum White Subtree~1800CF 1324F
Hint
down[v] = a[v] + Σ max(0, down[child]). Then full[child] = down[child] + max(0, full[v] - max(0, down[child])). - Tree with Maximum Cost~1900CF 1092F
Hint
res[child] = res[v] + total - 2·sub[child], where sub is the subtree weight sum. - Binary Tree Cameras~2100LC 968★ core
Hint
Three states per node: no camera and uncovered, covered without a camera, has a camera. Equivalently, greedily put cameras on the parents of leaves. - Sum of Distances in Tree~2200LC 834★ core
Hint
ans[child] = ans[v] - size[child] + (n - size[child]). Moving the root one step brings size[child] nodes closer and pushes the rest further away. - Minimum Edge Reversals So Every Node Is Reachable~2300LC 2858
Hint
Same as Treeland: forward edge costs 0, reverse costs 1, then reroot. - Count Number of Possible Root Nodes~2200LC 2581
Hint
Count the correct guesses for root 0. Moving the root from u to v changes only the guesses (u, v) and (v, u). - Longest Path With Different Adjacent Characters~2100LC 2246★ core
Hint
At each node keep the two longest child chains whose character differs from the node's. The answer is 1 + best1 + best2. - Create Components With Same Value~2400LC 2440★ core
Hint
The number of components must divide the total. For each divisor, DFS returns the subtree sum, cuts when the sum equals the target and fails when it goes over. - Difference Between Maximum and Minimum Price Sum~2400LC 2538
Hint
The cost is a path sum minus one endpoint. For each node keep two values: the best chain down that includes its leaf, and the best that excludes it. Combine at each node. - Karen and Supermarket~2400CF 815C
Hint
Tree knapsack: dp[v][k][coupon used?]. Merging children in order of size keeps the total at O(n²).
DP on DAGs
- Longest Increasing Path in a Matrix~2000LC 329
Hint
DFS with memoisation. Strictly increasing moves can't cycle, so no visited set is needed. - ~2100
- Largest Color Value in a Directed Graph~2300LC 1857★ core
Hint
Kahn's algorithm with dp[node][colour] = maximum count of that colour on any path ending at node. Return -1 if there's a cycle.
Extra-state DP (state machines)
- Best Time to Buy and Sell Stock IV~2000LC 188
Hint
dp[j][holding]. If k ≥ n/2 the limit doesn't bind, so treat it as unlimited. - Student Attendance Record II~2300LC 552★ core
Hint
States are (absences 0–1, trailing lates 0–2): 6 states, O(n). For huge n, use matrix exponentiation. - String Compression II~2600LC 1531
Hint
dp[i][k]: either delete s[i], or keep s[i] as the start of a run and scan ahead, deleting the characters that differ, while tracking the run length.
Probability & expectation
- Ilya and Escalator~1700CF 518D
Hint
dp[t][j] = probability that j people are on the escalator after t seconds. - ~1800
- Soup Servings~2000LC 808
Hint
Divide by 25. For n ≥ about 4800 the answer is 1 to within the allowed error. - New 21 Game~2350LC 837★ core
Hint
dp[x] = (sum of dp[x-maxPts .. x-1] restricted to values < k) / maxPts, kept as a sliding window sum. The answer is Σ dp[k..n].
DP optimisations
- Find the Longest Valid Obstacle Course at Each Position~1900LC 1964
Hint
Non-decreasing LIS: bisect_right on the tails array; the answer at i is the insert position + 1. - ~1950
- Maximum Profit in Job Scheduling~2000LC 1235★ core
Hint
Sort by end time. dp[i] = max(dp[i-1], profit[i] + dp[last job ending ≤ start[i]]), found by binary search. - Maximum Number of Events That Can Be Attended II~2000LC 1751
Hint
dp[i][k], with the next index found by binary search. - ~2050
- Russian Doll Envelopes~2100LC 354★ core
Hint
Sort by width ascending and height descending, so equal widths can't chain, then run strict LIS on the heights. - Shortest Subarray with Sum at Least K~2300LC 862★ core
Hint
Negative values rule out a sliding window. Keep prefix indices in a deque with increasing values; pop from the front while P[i] - P[front] ≥ k. - K Inverse Pairs Array~2300LC 629★ core
Hint
dp[n][k] = dp[n][k-1] + dp[n-1][k] - dp[n-1][k-n] (a prefix-sum telescope). - Kalila and Dimna in the Logging Industry~2100CF 319C
Hint
dp[i] = min over j of dp[j] + b[j]·a[i]. The slopes b decrease and the queries a increase, so a monotone convex hull trick deque works. - Yet Another Minimization Problem~2500CF 868F
Hint
The optimal split point is monotone, so use divide-and-conquer DP. Compute cost(l, r) with Mo-style moving pointers.
Counting & combinatorics
- Number of Ways to Rearrange Sticks With K Sticks Visible~2100LC 1866
Hint
Place the shortest stick last in reasoning: it's visible only if it comes first. dp[n][k] = dp[n-1][k-1] + (n-1)·dp[n-1][k]. - Number of Ways to Reorder Array to Get Same BST~2300LC 1569★ core
Hint
ways(T) = C(|L|+|R|, |L|) · ways(L) · ways(R). Subtract 1 for the original order. - ~2400
- Valid Permutations for DI Sequence~2400LC 903
Hint
dp[i][j] = number of ways where the last element has relative rank j among the first i+1. Prefix sums over j. - Count Ways to Build Rooms in an Ant Colony~2500LC 1916
Hint
The number of topological orders of a rooted tree is n! / ∏ size(v).
String DP
- Distinct Subsequences~1900LC 115
Hint
dp[i][j] = dp[i-1][j] + (s[i] == t[j]) · dp[i-1][j-1]. Iterate j backwards to use 1D. - Palindrome Partitioning II~2000LC 132★ core
Hint
Expand around each centre and update cut[r+1] = min(cut[r+1], cut[l] + 1). O(n²) with no palindrome table. - Distinct Subsequences II~2000LC 940★ core
Hint
total' = 2·total - (count just before the previous occurrence of this character). - Regular Expression Matching~2000LC 10
Hint
For 'x*': use it zero times (dp[i][j-2]), or once more if x matches (dp[i-1][j]). - Count Different Palindromic Subsequences~2600LC 730
Hint
Per character c: look at the first and last occurrence of c inside [l, r]. If there's none, one, or more than one, the recurrence differs. Don't double-count.
Game DP
- ~1800
- ~2000
- Cat and Mouse~2600LC 913★ core
Hint
State (mouse, cat, turn). Seed the known results (mouse at the hole, cat catches mouse) and propagate backwards: a state is a loss once all its moves lead to wins for the opponent. Whatever is left is a draw.
Grid & profile DP
- ~1950
- Painting a Grid With Three Different Colors~2200LC 1931★ core
Hint
m ≤ 5, so there are at most 48 valid columns. Build the compatibility matrix and run n steps. - Cherry Pickup~2300LC 741★ core
Hint
Going there and back equals two forward paths. dp[t][r1][r2], with c = t - r. - Maximize Grid Happiness~2650LC 1659
Hint
Broken profile: process one cell at a time with a base-3 code of the last n cells, plus the number of introverts and extroverts left.
Contribution technique
- Sum of Subarray Minimums~1950LC 907★ core
Hint
Monotonic stack gives left[i] and right[i]. The contribution is a[i] · left · right. - ~2000
- Count Unique Characters of All Substrings of a Given String~2050LC 828★ core
Hint
Each occurrence adds (i - prev) · (next - i).
Matrix exponentiation
- ~2100
Trees
Binary lifting & LCA
- Tree Queries~1900CF 1328E★ core
Hint
Replace each query vertex with its parent, then check they all lie on the root path to the deepest one, using tin and tout. - ~2100
- Minimum Edge Weight Equilibrium Queries in a Tree~2550LC 2846★ core
Hint
Keep a count of each weight 1..26 from the root to every node. Path count = c[u] + c[v] - 2·c[lca]. Answer = path length - largest count.
Euler tour + segment tree / BIT
- Vasya and a Tree~1900CF 1076E
Hint
Offline DFS with a difference array indexed by depth: add on entry, undo on exit. - New Year Tree~2100CF 620E★ core
Hint
A segment tree over the Euler tour storing a 60-bit colour mask, with lazy assignment. Answer with popcount. - Propagating tree~2000CF 383C
Hint
Value signs alternate by depth parity. Use a BIT range update over the subtree, with the sign set by depth.
Small-to-large (DSU on tree)
- Tree Requests~2200CF 570D
Hint
Bucket nodes by depth in tin order and binary search the subtree range. A palindrome is possible if the XOR of letter parities has at most 1 bit set. - Lomsat gelral~2300CF 600E★ core
Hint
Small-to-large on maps of colour counts, carrying (best frequency, sum of colours with it).
Centroid decomposition & HLD
- Ciel the Commander~2100CF 321C
Hint
Rank = depth in the centroid tree. It's always possible because the depth is at most log n ≤ 26. - Water Tree~2100CF 343D
Hint
Fill a subtree = range assign on the Euler tour. Empty the path to the root = HLD path assign. - Xenia and Tree~2400CF 342E★ core
Hint
For each centroid ancestor c of the painted node, best[c] = min(best[c], dist). A query takes the min of best[c] + dist(v, c).
Peeling leaves, diameter & centres
- Minimum Height Trees~1800LC 310
Hint
Peel leaves layer by layer; the last 1 or 2 nodes left are the centres. - Count Subtrees With Max Distance Between Cities~2300LC 1617
Hint
n ≤ 15. Enumerate subsets, check each is connected, and take its diameter from Floyd-Warshall distances. - Collect Coins in a Tree~2700LC 2603★ core
Hint
Repeatedly remove leaves without coins, then strip 2 more layers of leaves. The answer is 2 · (edges remaining).
Binary tree tricks
- Recover a Tree From Preorder Traversal~1800LC 1028
Hint
Count the dashes to get the depth, then use a stack trimmed to that depth. - ~1900
- Height of Binary Tree After Subtree Removal Queries~2300LC 2458★ core
Hint
Two DFS passes: left-first and right-first, each carrying the maximum height reached so far before entering a node. The answer for a node combines what lies outside its subtree.
Tree XOR & edge removal
- Find the Maximum Sum of Node Values~2250LC 3068★ core
Hint
XORing along a path toggles only its two endpoints, so you can toggle any even-size set of nodes. Greedy or DP on parity; the tree shape doesn't matter. - Minimum Score After Removals on a Tree~2400LC 2322
Hint
Precompute subtree XORs and tin/tout. Try all O(n²) pairs of edges, using the ancestor test to work out the three components.
Trie (bitwise)
- ~1800
- ~2000
- Maximum XOR With an Element From Array~2350LC 1707★ core
Hint
Offline: sort the queries by m and insert numbers ≤ m as you go. - Maximum Genetic Difference Query~2500LC 1938
Hint
Offline DFS: insert a node on entry, answer the queries at that node, delete it on exit.
Graphs
0-1 BFS & state-space Dijkstra
- Cheapest Flights Within K Stops~1800LC 787
Hint
Bellman-Ford for k+1 rounds, copying the distance array each round. - Shortest Path in a Grid with Obstacles Elimination~1950LC 1293
Hint
BFS over (r, c, eliminations left). If k ≥ m + n - 2, return the Manhattan distance. - Minimum Cost to Make at Least One Valid Path in a Grid~2100LC 1368★ core
Hint
0-1 BFS: following a cell's arrow costs 0, any other direction costs 1. - Number of Ways to Arrive at Destination~2100LC 1976★ core
Hint
Dijkstra that also counts ways: on a tie, ways[v] += ways[u]; on an improvement, reset. - Minimum Obstacle Removal to Reach Corner~2150LC 2290
Hint
0-1 BFS where a cell's weight is whether it's an obstacle. - Second Minimum Time to Reach Destination~2200LC 2045★ core
Hint
BFS keeping the first two distinct arrival distances per node, then simulate the red/green traffic signals for that number of edges. - Reachable Nodes In Subdivided Graph~2300LC 882
Hint
Dijkstra on the original nodes. Edge (u, v, cnt) adds min(cnt, max(0, M - d[u]) + max(0, M - d[v])). - Minimum Time to Visit a Cell In a Grid~2400LC 2577★ core
Hint
If both neighbours of the start are blocked, return -1. Otherwise you can wait by stepping back and forth, so the arrival time is raised to the cell's time, adjusted for parity. - Minimum Path~2400CF 1473E★ core
Hint
sum - max + min equals using one edge twice and another edge zero times. Run Dijkstra over (v, doubled used?, zeroed used?), with 4 layers.
Multi-source & reverse-graph shortest paths
- Find the Safest Path in a Grid~2150LC 2812★ core
Hint
Multi-source BFS from the thieves gives a safety grid. Then find the max-min path with a max-heap Dijkstra or binary search + BFS. - Minimum Weighted Subgraph With the Required Paths~2350LC 2203★ core
Hint
Three Dijkstras: from src1, from src2, and from dest on the reversed graph. Answer = min over meeting node x of the three distances summed.
Bridges, articulation points, SCC, 2-SAT
- Checkposts~1700CF 427C
Hint
Within each SCC, take the minimum cost and count how many nodes have it; multiply the counts. - ~2100
- Bertown roads~2000CF 118E
Hint
Possible if and only if there are no bridges. Orient tree edges downward and back edges upward. - The Door Problem~2000CF 776D
Hint
Each door is controlled by exactly 2 switches, which gives an XOR constraint. Use a parity DSU, or 2-colouring. - Minimum Number of Days to Disconnect Island~2200LC 1568★ core
Hint
The answer is always 0, 1 or 2. Check whether it's already disconnected, then try removing each cell.
Offline DSU & processing by value
- Path Queries~1800CF 1213G
Hint
Sort the edges; each union adds size[a] · size[b] pairs. Answer the sorted queries as you sweep. - Minimize Malware Spread II~2000LC 928
Hint
For each infected node, BFS while avoiding the other infected nodes. Count the clean nodes reached only from this one. - Remove Max Number of Edges to Keep Graph Fully Traversable~2150LC 1579
Hint
Add type-3 edges to both DSUs first, then type 1 and type 2. - Checking Existence of Edge Length Limited Paths~2300LC 1697★ core
Hint
Offline: sort the queries by limit and add edges with weight < limit. - Number of Good Paths~2450LC 2421★ core
Hint
Activate nodes in increasing value, uniting each with neighbours of value ≤ its own. For each value, a component with c such nodes adds C(c, 2) + c paths. - Bricks Falling When Hit~2750LC 803
Hint
Reverse time. Remove every hit, union the remaining bricks (with a virtual roof node), then add the hits back in reverse and measure how much the roof component grows.
MST tricks
- ~1900
- Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree~2550LC 1489★ core
Hint
For each edge, run Kruskal without it (critical if the weight rises or the graph disconnects) and with it forced in (pseudo-critical if the weight equals the base).
Topological sort variants
- Build a Matrix With Conditions~1950LC 2392
Hint
Two independent topological sorts, one for rows and one for columns. - Sort Items by Groups Respecting Dependencies~2400LC 1203★ core
Hint
Two-level topological sort: groups first, then items within each group.
Euler paths (Hierholzer)
- ~2000
- Cracking the Safe~2300LC 753★ core
Hint
De Bruijn sequence: an Euler circuit over the (n-1)-digit prefixes. - ~2650
Functional graphs (out-degree 1)
- Longest Cycle in a Graph~1900LC 2360
Hint
Walk from each unvisited node, stamping times. Revisiting a node from the current walk gives the cycle length as the time difference. - Count Visited Nodes in a Directed Graph~2200LC 2876★ core
Hint
Nodes on a cycle get the cycle length. The rest get 1 + ans[next], computed in topological peel order. - Maximum Employees to Be Invited to a Meeting~2450LC 2127★ core
Hint
The answer is max(the largest cycle of length ≥ 3, the sum over all 2-cycles of 2 + the longest chains into both ends). - Maximize Value of Function in a Ball Passing Game~2750LC 2836
Hint
k goes up to 1e10. Binary lifting storing (node after 2^j steps, sum of ids along the way).
BFS on implicit state
- Bus Routes~1950LC 815★ core
Hint
BFS over routes rather than stops. Map each stop to its routes and mark each route used once. - ~2250
- Minimum Moves to Move a Box to Their Target Location~2300LC 1263
Hint
BFS over (box position, player side). For each push, run an inner BFS to check the player can reach the pushing cell.
Bipartite & layering
- Divide Nodes Into the Maximum Number of Groups~2400LC 2493★ core
Hint
If any component isn't bipartite, return -1. Otherwise sum, over components, the maximum BFS depth from any start node in it.
Minimax paths
- Swim in Rising Water~2100LC 778★ core
Hint
Union cells in order of height until the start and end are connected; equivalently, Dijkstra with max.