Skip to main content

Advanced Dynamic Programming

Beyond basic 1D/2D DP — patterns that appear in harder interview and competitive programming problems.

DP on Trees

Process tree structures bottom-up or top-down using DFS.

Pattern

Classic Problems

  • Binary Tree Maximum Path Sum
  • House Robber III
  • Diameter of Binary Tree
  • Longest Path in a Tree
  • Count Nodes in Complete Tree with property X

DP on Graphs

DP over DAGs using topological order, or shortest path problems with state.

Key Insight

  • If the graph is a DAG, topological sort gives a valid DP ordering
  • Otherwise, look for ways to define states that form a DAG (e.g., adding constraints)

Classic Problems

  • Longest Path in a DAG
  • Cheapest Flights Within K Stops
  • Shortest Path with constraints
  • Number of ways to reach destination

Digit DP

Count numbers in range [L, R] with specific digit properties.

Pattern

State: (position, tight, started, ...custom_state)
  • tight: are we still bounded by the upper limit?
  • started: have we placed a non-zero digit yet? (for leading zeros)

Classic Problems

  • Numbers At Most N Given Digit Set
  • Count Numbers with Unique Digits
  • Numbers With Repeated Digits
  • Non-negative Integers without Consecutive Ones

Bitmask DP

Use a bitmask to represent subsets of a small set (n ≤ 20).

Key Idea

State includes a bitmask representing which elements have been used/visited.
  • Time: O(2^n × n), Space: O(2^n × n)
  • n must be small (typically ≤ 20)

Classic Problems

  • Travelling Salesman Problem
  • Partition to K Equal Sum Subsets
  • Shortest Path Visiting All Nodes
  • Can I Win
  • Minimum Cost to Visit Every Node in a Graph

When to Use Which