Docsity

Dynamic Programming (DP) Master Guide — Core Patterns, Visual Traces & Python Code Templat, Study Guides, Projects, Research of Data Structures and Algorithms

Toggle sidebar
bg1
Dynamic Programming (DP) Master Guide
— Core Patterns, Step-by-Step Visual
Traces & Python Templates
CS 301 / Algorithms & Data Structures / Technical Coding Interview Study Manual
Table of Contents
1. Quick-Reference High-Yield DP Patterns Matrix
2. The 5-Step Dynamic Programming Framework
3. Pattern 1: 0/1 Knapsack & Subset State Transitions
4. Pattern 2: Unbounded Knapsack & Coin Optimization
5. Pattern 3: Longest Common Subsequence (LCS) & String Alignment
6. Pattern 4: Longest Increasing Subsequence (LIS) & Binary Search Acceleration
7. Pattern 5: Matrix Pathfinding & Grid DP
8. Common DP Bugs, Memory Optimization & Exam Pitfalls
1. Quick-Reference High-Yield DP Patterns Matrix
Pattern Name Recurrence / State Strategy Space Optimization Typical Problem Framings
0/1 Knapsack dp[i][w] = max(dp[i-1][w],
val + dp[i-1][w-wt])
O(W) 1D Array (Iterate Backwards) Bounded item selection, Partition
subset equal sum, Target sum
Unbounded Knapsack dp[w] = max(dp[w], val +
dp[w-wt])
O(W) 1D Array (Iterate Forwards) Coin change, Rod cutting,
Minimum items to total
LCS (Strings) dp[i][j] = dp[i-1][j-1]+1 if
match else max
O(min(M, N)) 2 Rows Edit distance, Shortest common
supersequence, Alignment
LIS (Subsequence) dp[i] = max(1 + dp[j]) for j
< i
O(N) or O(N log N) via Binary
Search
Russian doll envelopes, Longest
chain building, Milestone
sequences
Grid Pathfinding dp[r][c] = cell + min(dp[r-
1][c], dp[r][c-1])
O(C) 1D Row Minimum path sum, Unique paths
with obstacles, Dungeon game
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Dynamic Programming (DP) Master Guide — Core Patterns, Visual Traces & Python Code Templat and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity!

Dynamic Programming (DP) Master Guide

— Core Patterns, Step-by-Step Visual

Traces & Python Templates

CS 301 / Algorithms & Data Structures / Technical Coding Interview Study Manual

Table of Contents

1. Quick-Reference High-Yield DP Patterns Matrix

2. The 5-Step Dynamic Programming Framework

3. Pattern 1: 0/1 Knapsack & Subset State Transitions

4. Pattern 2: Unbounded Knapsack & Coin Optimization

5. Pattern 3: Longest Common Subsequence (LCS) & String Alignment

6. Pattern 4: Longest Increasing Subsequence (LIS) & Binary Search Acceleration

7. Pattern 5: Matrix Pathfinding & Grid DP

8. Common DP Bugs, Memory Optimization & Exam Pitfalls

1. Quick-Reference High-Yield DP Patterns Matrix

Pattern Name Recurrence / State Strategy Space Optimization Ty 0/1 Knapsack (^) dp[i][w] = max(dp[i-1][w], val + dp[i-1][w-wt]) O(W) 1D Array (Iterate Backwards) Bo su Unbounded Knapsack (^) dp[w] = max(dp[w], val + dp[w-wt]) O(W) 1D Array (Iterate Forwards) Co Mi LCS (Strings) (^) dp[i][j] = dp[i-1][j-1]+1 if match else max O(min(M, N)) 2 Rows Ed su LIS (Subsequence) (^) dp[i] = max(1 + dp[j]) for j < i O(N) or O(N log N) via Binary Search Ru ch se Grid Pathfinding (^) dp[r][c] = cell + min(dp[r- 1][c], dp[r][c-1]) O(C) 1D Row Mi wi

2. The 5-Step Dynamic Programming Framework Every Dynamic Programming problem can be decomposed systematically using the following five- step pipeline:

● Step 1: Define the State Variable clearly. Identify what parameters uniquely define a

subproblem. Express this as dp[i] or dp[i][j], defining in plain language exactly what value is stored at that index (e.g., "The minimum cost to reach step i").

● Step 2: Formulate the State Transition Equation. Establish the mathematical relationship

connecting the target state to previously solved smaller subproblems. Express choices explicitly (e.g., take vs. skip).

● Step 3: Identify Base Cases and Boundary Conditions. Determine the smallest atomic

subproblems that require no prior calculation (e.g., dp[0] = 0, boundary zero-padding). Guard against out-of-bounds index access.

● Step 4: Determine Traversal Direction & Ordering. Decide whether to use Top-Down

Memoization (recursion + caching) or Bottom-Up Tabulation (iterative loops). Ensure dependencies are fully evaluated before evaluating dependent states.

● Step 5: Apply Space Complexity Reduction. Reduce 2D memory layouts down to 1D

arrays (or variables) whenever state transitions only rely on immediate previous rows or constant previous states.

3. Pattern 1: 0/1 Knapsack & Subset State Transitions Rephrased Problem Statement: Optimal Resource Vault Allocation Given a set of items, each with a designated weight (item_masses) and monetary value (item_profits), determine the maximum total profit achievable without exceeding a fixed maximum vault capacity (vault_capacity). Each item can be taken at most once (0/1 choice). Python Implementation (Tabulation & 1D Space-Optimized) def optimal_vault_allocation(item_masses: list[int], item_profits: list[int], vault_capacity: int) -> int: """ Computes the maximum profit for a bounded capacity vault. Uses a 1D array traversed backwards to enforce 0/1 single-use constraints. """

Final Answer at index 5: 7 (Items 1 & 2 selected) EXAM WARNING: 1D Array Loop Direction in 0/1 Knapsack When optimizing 0/1 Knapsack to a 1D array, you must iterate backwards from vault_capacity down to current_mass. Iterating forwards causes values updated in the current outer loop iteration to overwrite smaller capacity entries, causing the same item to be counted repeatedly.

4. Pattern 2: Unbounded Knapsack & Coin Optimization Rephrased Problem Statement: Minimum Currency Denominations for Exact Vault Settlement You are given an array of available currency denominations (coin_values) and a target amount (settlement_target). Return the minimum number of coins needed to make up that exact amount. You have an unlimited supply of each coin denomination. If the amount cannot be made up, return -1. Python Implementation def minimum_coins_for_settlement(coin_values: list[int], settlement_target: int) -> int: # Use infinity as sentinel value for unreachable states infinity = float('inf') dp_min_coins = [infinity] * (settlement_target + 1) # Base Case: 0 cost to form an amount of 0 dp_min_coins[0] = 0 # Forward iteration allows infinite reuse of coin denominations for amount in range(1, settlement_target + 1): for coin in coin_values:

if amount - coin >= 0: dp_min_coins[amount] = min( dp_min_coins[amount], 1 + dp_min_coins[amount - coin] ) return dp_min_coins[settlement_target] if dp_min_coins[settlement_target] != infinity else - TIME COMPLEXITY INSIGHT & COMMON BUG

● Time Complexity: O(N * T) where N is the number of coins and T is the target amount.

● Space Complexity: O(T) 1D array state space.

● Forward Iteration: Forward loop traversal explicitly allows an item/coin to be selected

repeatedly in the same pass.

● Initialization Bug: For minimization DP problems, always initialize unused states to infinity

(float('inf')) while keeping dp[0] = 0. Initializing with 0 will break min() operations.

5. Pattern 3: Longest Common Subsequence (LCS) Rephrased Problem Statement: DNA Strand Structural Alignment Match Given two biological sequences strand_alpha and strand_beta, compute the length of their longest common subsequence. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. Python Implementation (2D Tabulation) def longest_common_dna_subsequence(strand_alpha: str, strand_beta: str) -> int: len_a, len_b = len(strand_alpha), len(strand_beta) # Create 2D DP table initialized with zeros

6. Pattern 4: Longest Increasing Subsequence (LIS) Rephrased Problem Statement: Longest Monotonic Increasing Milestone Sequence Given an array of integer project evaluation milestones, find the length of the longest strictly increasing sequence of milestones. Method 1: Classic Dynamic Programming — O(N²) Time Complexity def lis_classic(milestones: list[int]) -> int: if not milestones: return 0 n = len(milestones) dp = [1] * n # Base case: Each element alone is an LIS of length 1 for i in range(1, n): for j in range(i): if milestones[j] < milestones[i]: dp[i] = max(dp[i], 1 + dp[j]) return max(dp) Method 2: Patience Sorting & Binary Search Acceleration — O(N log N) Time Complexity def lis_binary_search(milestones: list[int]) -> int: from bisect import bisect_left

tails = [] for x in milestones:

Find the insertion index of x in tails array to maintain sorted order

idx = bisect_left(tails, x) if idx == len(tails): tails.append(x) else: tails[idx] = x # Overwrite existing tail value with smaller candidate return len(tails) EXAM TIP: Subsequence vs. Subarray

● Subarray / Substring: Must be contiguous in the original array (e.g., sliding window

techniques or Kadane's algorithm).

● Subsequence: Elements maintain relative order but do not need to be contiguous (e.g.,

standard 2D LCS or LIS patterns).

7. Pattern 5: Matrix Pathfinding & Grid DP Rephrased Problem Statement: Minimal Hazard Grid Traversal Given an M x N grid filled with non-negative hazard traversal costs, find a path from the top-left cell (0, 0) to the bottom-right cell (M-1, N-1) that minimizes total hazard cost. You can only move either down or right at any step.

return dp[rows - 1][cols - 1] Visual Step Trace Hazard Input Grid: Calculated Min-Cost Grid: [1, 3, 1] [ 1, 4, 5] [1, 5, 1] ---------> [ 2, 7, 6] [4, 2, 1] [ 6, 8, 7] <-- Answer: 7

8. Common DP Bugs & Exam Review Checklist High-Frequency Bugs & Pitfalls +------------------------------------ +---------------------------------------------------------------+ | Common DP Bug / Mistake | Cause & Fix | +------------------------------------ +---------------------------------------------------------------+ | Index Out of Bounds | Forgetting size +1 padding when using 1-based indexing tables.| | Overwriting States in 1D Arrays | Iterating forward instead of backward in bounded 0/1 DP. | | Incorrect Infinity Sentinel Values | Using 999999 instead of float('inf') causing incorrect min(). | | Missing Subproblem Overlap | Applying DP to non-overlapping states (use Divide & Conquer). | +------------------------------------ +---------------------------------------------------------------+ Final Exam Review Checklist State Definition: Can you explain dp[i] in a single, precise sentence?

Base Cases: Have zero-indexes, empty string inputs, or invalid capacity cases been explicitly handled? Loop Directions: Is 0/1 Knapsack iterated backwards, and Unbounded iterated forwards? Substructure Property: Does solving the global optimal solution rely strictly on optimal solutions to smaller subproblems? Space Complexity Check: Can your 2D table be compressed to 1D using state reduction?