Skip to lesson

Comprehensive advanced DP practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

In this comprehensive capstone practice lesson, we synthesize all advanced dynamic programming techniques. We examine how input constraints reveal the correct paradigm and tackle multi-faceted interview challenges.

Constraint Clues and Paradigm Classification

The fastest way to identify the intended dynamic programming approach in an interview is examining the problem constraints. When N is up to 20, bitmask DP is likely because 2^20 is roughly 1 million states. When N is up to 500, interval DP running in O(N^3) fits within 10^8 operations.

When N is up to 100,000 on a hierarchical structure, tree DP running in O(N) post-order time is standard. If the problem asks for extrema across sliding windows of size K, monotonic queues optimize transitions to O(N).

Finally, when N is astronomical up to 10^18, digit DP handles bounded decimal counting in milliseconds, while matrix exponentiation computes linear recurrences in logarithmic O(K^3 log N) time.

Interval DP Multi-Pile Stone Merging

In Minimum Cost to Merge Stones, we merge K consecutive piles into one pile at cost equal to their sum, repeating until one pile remains. Why does plain greedy merging fail? Merging the currently smallest piles can lock you into expensive late merges.

Example 1 · Minimum Cost to Merge Stones (K=2)

MergeStonesDemo.javaJava
public class MergeStonesDemo {    public static int mergeStones(int[] stones) {        int n = stones.length;        int[] pref = new int[n + 1];        for (int i = 0; i < n; i++) pref[i + 1] = pref[i] + stones[i];
        int[][] dp = new int[n][n];
        for (int len = 2; len <= n; len++) {            for (int i = 0; i <= n - len; i++) {                int j = i + len - 1;                dp[i][j] = Integer.MAX_VALUE;                for (int m = i; m < j; m++) {                    dp[i][j] = Math.min(dp[i][j], dp[i][m] + dp[m + 1][j]);                }                dp[i][j] += pref[j + 1] - pref[i];            }        }        return dp[0][n - 1];    }
    public static void main(String[] args) {        int[] stones = {3, 2, 4, 1};        System.out.println("Min cost to merge stones: " + mergeStones(stones));    }}
Output
Min cost to merge stones: 20

What this code does

  • Uses interval length expansion from len = 2 up to n.
  • Splits range [i, j] at all possible midpoints m and adds subarray sum.
  • Merges {3, 2, 4, 1} in optimal order: {3, 2}->5 (cost 5), {4, 1}->5 (cost 5), {5, 5}->10 (cost 10) = 20.

Interval DP evaluates subarrays [i, j]. Because every move reduces pile count by K - 1, a range [i, j] can be reduced to 1 pile if and only if (j - i) % (K - 1) == 0. We define dp[i][j][m] as the minimum cost to reduce subarray [i..j] to m piles. Splitting the range at intermediate cut p merges the left part into 1 pile and the right into m - 1 piles.

Tree DP Domination and State Triads

In Binary Tree Cameras, we place the minimum number of cameras to monitor all nodes, where each camera monitors itself, its parent, and its immediate children. A naive greedy approach from top to bottom fails because leaf nodes have fewer neighbors.

Example 2 · Binary Tree Cameras Post-Order DP

TreeCamerasDemo.javaJava
public class TreeCamerasDemo {    private static int cameras = 0;
    // 0: Uncovered, 1: Has camera, 2: Covered without camera    public static int minCameraCover(TreeNode root) {        cameras = 0;        if (dfs(root) == 0) cameras++;        return cameras;    }
    private static int dfs(TreeNode node) {        if (node == null) return 2; // Null nodes are considered covered
        int left = dfs(node.left);        int right = dfs(node.right);
        if (left == 0 || right == 0) {            cameras++;            return 1;        }        if (left == 1 || right == 1) {            return 2;        }        return 0;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(0);        root.left = new TreeNode(0);        root.left.left = new TreeNode(0);        root.left.right = new TreeNode(0);        System.out.println("Min cameras: " + minCameraCover(root));    }
    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { this.val = v; }    }}
Output
Min cameras: 1

What this code does

  • Returns state triad: 0=uncovered, 1=has camera, 2=covered.
  • Places camera at node if either child is uncovered to maximize coverage.
  • Root node gets an extra camera if left uncovered after DFS traversal.

We solve this bottom-up using tree DP. Each node returns one of three states to its parent: 0 if uncovered, 1 if hosting a camera, or 2 if covered without a camera. If either child returns 0 (uncovered), the current node must place a camera (state 1). If either child has a camera (state 1), the current node is safely covered (state 2). Otherwise, the node remains uncovered (state 0), deferring camera placement to its parent.

Bitmask BFS for All-Node Traversal

Finding the shortest path visiting all nodes in a graph cannot be solved by plain BFS because nodes may need to be visited multiple times. However, visiting a node twice with the exact same subset of visited vertices is redundant.

Example 3 · Shortest Path Visiting All Nodes via Bitmask BFS

ShortestPathAllNodesDemo.javaJava
import java.util.ArrayDeque;import java.util.Queue;
public class ShortestPathAllNodesDemo {    public static int shortestPathLength(int[][] graph) {        int n = graph.length;        if (n <= 1) return 0;
        int target = (1 << n) - 1;        boolean[][] visited = new boolean[n][1 << n];        Queue<int[]> queue = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {            queue.offer(new int[]{i, 1 << i, 0});            visited[i][1 << i] = true;        }
        while (!queue.isEmpty()) {            int[] curr = queue.poll();            int u = curr[0], mask = curr[1], dist = curr[2];
            if (mask == target) return dist;
            for (int v : graph[u]) {                int nextMask = mask | (1 << v);                if (!visited[v][nextMask]) {                    visited[v][nextMask] = true;                    queue.offer(new int[]{v, nextMask, dist + 1});                }            }        }        return -1;    }
    public static void main(String[] args) {        int[][] graph = {{1, 2, 3}, {0}, {0}, {0}};        System.out.println("Shortest path visiting all nodes: " + shortestPathLength(graph));    }}
Output
Shortest path visiting all nodes: 4

What this code does

  • State (u, mask) tracks current node and bitmask of visited nodes.
  • Multi-source BFS starts with all single-node states at distance 0.
  • Star graph with center 0 requires visiting 0 multiple times: path length 4.

We define the state as a pair (u, mask) where u is the current vertex and mask is a bitmask of all vertices visited so far. The state space has size N * 2^N. Because all edge weights are 1, running Breadth-First Search on the state graph finds the shortest path visiting all nodes in O(N * 2^N) time. The first state dequeued with mask == (1 << N) - 1 gives the exact shortest distance.

Finish up

Mark complete & continue

Next: Searching text