Dynamic Programming
dynamic-programming
Algorithms
Advanced Bit Manipulation
Iterating over all subsets of every subset of an `n`-element set sounds like `4^n` work. The actual cost is `3^n`: each element is in three states (in the outer mask only, in both, or in neither), and the binomial theorem collapses the sum. Insights like that turn what looks like a complexity wall into a tight, elegant solution. **Advanced Bit Manipulation** collects those insights. You will generate Gray codes (adjacent values differ by one bit, used in error correction), enumerate all subsets of a bitmask via the `for (s = mask; s > 0; s = (s - 1) & mask)` template, and master bit tricks like isolating the lowest set bit with `x & -x`, turning it off with `x & (x - 1)`, counting trailing zeros, and swapping without a temp variable. The lesson also covers advanced XOR applications (range XOR, two missing numbers, XOR basis over GF(2)) and bitwise DP including profile DP for grid tiling. In **Bit Manipulation (Intro)**, you mastered the basic operators and the single-number XOR trick. This lesson treats bits as a full algorithmic medium. Next, **Complexity & Proof Intuition (Optional)** revisits the theoretical foundations behind everything built so far.
Not Started
0%
Dynamic Programming (Advanced)
Edit distance, the minimum number of insertions, deletions, and substitutions to turn one string into another, is what every spell checker quietly computes when it suggests a correction. The DP table that solves it has `m * n` cells, each filled by looking at three neighbors. That single 2D recurrence is the gateway to a much larger family: longest common subsequence, knapsack, palindrome partitioning, regex matching, and many more. **Dynamic Programming (Advanced)** is where 1D DP graduates into the rest of the field. You will work through 2D grid and string DP (unique paths, edit distance, LCS, longest common substring), the knapsack family (0/1, unbounded, subset sum, coin change), sequence DP (LIS in `O(n^2)` and the patience-sorting `O(n log n)` variant, maximum product subarray, word break), string DP (palindromic subsequence and substring, regex and wildcard matching), DP on trees (diameter, max path sum, binary tree cameras), interval DP via matrix chain multiplication, and an introduction to bitmask DP for TSP and assignment problems. In **Dynamic Programming (Intro)**, you learned to define state, transition, and base cases on linear problems. This lesson layers a second dimension onto each. Next, **Advanced DP Techniques** introduces optimization tools that push DP beyond standard tabulation.
Not Started
0%
Dynamic Programming (Intro)
Naive recursive Fibonacci computes `fib(40)` in seconds, `fib(50)` in minutes, and gives up on `fib(60)`, all because it recomputes the same subproblems exponentially many times. Cache the result of each `fib(k)` the first time you compute it and the same recursion runs in linear time. That single change, remembering answers, is the entire content of dynamic programming. **Dynamic Programming (Intro)** turns that observation into a complete problem-solving framework. You will identify overlapping subproblems and optimal substructure (the two properties a problem must have for DP to apply), and master both approaches: top-down memoization (recursion plus a cache) and bottom-up tabulation (iteratively filling a table). Classic 1D problems include Fibonacci, climbing stairs, coin change, house robber, and a first look at Kadane's algorithm. The lesson teaches you to define state precisely ("what does `dp[i]` represent?"), write the transition ("how does `dp[i]` follow from earlier states?"), set base cases, and apply rolling-variable space optimization that drops `O(n)` to `O(1)`. In **Recursion Fundamentals**, you treated each recursive call as a stack frame. Memoization just attaches a cache so identical inputs return immediately. Next, **Bit Manipulation (Intro)** turns to a different toolkit, where bitwise operators give elegant `O(1)` solutions.
Not Started
0%
Advanced DP Techniques
Standard tabulation gets you `O(n^2)` DP. The Convex Hull Trick brings the same recurrence down to `O(n log n)` whenever the transition is a linear function of the previous state, and the speedup matters: contest problems with `n = 10^5` go from too-slow to fast enough on exactly that change. A whole sub-field of DP is dedicated to these recurrence-shaped optimizations, and this lesson is your entry into it. **Advanced DP Techniques** covers four directions of post-tabulation DP. Optimization methods include the Convex Hull Trick (offline sorted-slope and online Li Chao tree), Divide and Conquer DP for monotone-split problems, and Knuth's Optimization for optimal-BST-style recurrences. Digit DP teaches you how to count numbers with properties in a range `[L, R]` by carrying a tight-constraint flag through the recursion. Advanced bitmask DP solves TSP, Hamiltonian path, and grid-tiling profile DP. Probability DP turns recurrences over expected values into clean tables, and Kadane's algorithm generalizes to circular and 2D variants. In **Dynamic Programming (Advanced)**, you mastered multi-dimensional state and transitions. This lesson asks the next question: when the table is too big or the transition too slow, how do you optimize? Next, **Graph Algorithms (Advanced)** brings similar depth to graph theory.
Not Started
0%
Game Theory
Two players take turns removing stones from piles, the player who takes the last stone wins, and the entire winning strategy boils down to one calculation: XOR all pile sizes together, and you win if and only if the result is non-zero. That is Nim, and the surprise is not that it has a strategy but that the strategy is so compact. The Sprague-Grundy theorem extends the same idea to every impartial combinatorial game. **Game Theory** introduces the algorithmic side of two-player game analysis. You will work through Nim and its XOR strategy, then see how the Sprague-Grundy theorem assigns a Grundy number (nimber) to every position and how XOR-of-nimbers solves any sum of games. The lesson then moves to general game trees: minimax for optimal play, alpha-beta pruning for cutting branches that cannot affect the result, and move ordering for better pruning. You will analyze game states using DP, classifying positions as winning or losing by computing backward from terminal states, and meet retrograde analysis as a complete-game-state technique. In **Dynamic Programming (Intro)**, you learned to recurse on subproblems and cache results. **Recursion Fundamentals** gave you the call-stack model behind minimax and Grundy computation. Game theory recasts those tools as adversarial search. Next, **Randomized Algorithms** turns to a different way of taming worst-case inputs.
Not Started
0%
Practice Problems
Climbing Stairs
Given n steps, find the number of distinct ways to climb to the top when you can take 1 or 2 steps at a time.
Counting Bits
Given an integer n, return an array of length n + 1 where each element ans[i] is the number of 1s in the binary representation of i.
Min Cost Climbing Stairs
Given an array of step costs, find the minimum cost to reach the top of the staircase starting from step 0 or step 1.
Binary Tree Maximum Path Sum
Given the root of a binary tree, return the maximum path sum where a path is any sequence of connected nodes (not necessarily passing through the root).
Burst Balloons
Given n balloons with numbers on them, burst them wisely to maximize the total coins collected, where bursting balloon i earns nums[left] * nums[i] * nums[right].
Distinct Subsequences
Given two strings s and t, return the number of distinct subsequences of s which equals t.
Longest Increasing Path in a Matrix
Given an m x n integer matrix, find the length of the longest strictly increasing path where you can move in four directions.
Maximum Profit in Job Scheduling
Given jobs with start times, end times, and profits, find the maximum profit you can earn by scheduling non-overlapping jobs.
Maximal Rectangle
Given a 2D binary matrix filled with '0's and '1's, find the area of the largest rectangle containing only '1's.
Regular Expression Matching
Implement regular expression matching with support for '.' (matches any single character) and '*' (matches zero or more of the preceding element).
Best Time to Buy and Sell Stock III
Find the maximum profit from at most two stock transactions, where you must sell before buying again.
Best Time to Buy and Sell Stock IV
Find the maximum profit from at most k stock transactions, generalizing the Stock III problem to arbitrary k.
Cheapest Flights Within K Stops
Find the cheapest price to fly from a source to a destination with at most k intermediate stops, given a list of flights with prices.
Coin Change II
Given an array of coin denominations and a target amount, return the number of distinct combinations that make up that amount. Each coin may be used an unlimited number of times.
Coin Change
Given an array of coin denominations and a target amount, return the fewest number of coins needed to make up that amount, or -1 if it cannot be made.
Decode Ways
Given a string of digits, determine the total number of ways to decode it, where 'A' = 1, 'B' = 2, ..., 'Z' = 26.
Edit Distance
Given two strings word1 and word2, return the minimum number of operations (insert, delete, or replace a character) required to convert word1 into word2.
House Robber II
Houses are arranged in a circle. Adjacent houses cannot be robbed on the same night, and the first and last houses are also adjacent. Determine the maximum amount of money you can rob.
House Robber
Given an array representing the amount of money in each house along a street, determine the maximum amount you can rob without robbing two adjacent houses.
Interleaving String
Given three strings s1, s2, and s3, determine whether s3 is formed by interleaving s1 and s2 while preserving the relative order of characters from each string.
Jump Game
Given an integer array where each element represents the maximum jump length from that position, determine if you can reach the last index starting from the first index.
Longest Common Subsequence
Given two strings, return the length of their longest common subsequence. A subsequence is a sequence that can be derived by deleting some (or no) characters without changing the order of the remaining characters.
Longest Increasing Subsequence
Given an integer array, return the length of the longest strictly increasing subsequence.
Longest Palindromic Substring
Given a string, return the longest substring that reads the same forwards and backwards.
Maximum Product Subarray
Given an integer array, find the contiguous subarray within the array that has the largest product, and return that product.
Maximum Sum Circular Subarray
Given a circular integer array, find the maximum possible sum of a non-empty subarray that may wrap around the ends of the array.
Maximum Subarray
Given an integer array, find the subarray with the largest sum and return its sum.
Minimum Path Sum
Given an m x n grid filled with non-negative numbers, find a path from the top-left to the bottom-right that minimizes the sum of all numbers along the path.
Palindrome Partitioning
Given a string, partition it such that every substring of the partition is a palindrome. Return all possible palindrome partitions.
Palindromic Substrings
Given a string, return the number of substrings that are palindromes. Each unique start-end position counts as a different substring even if the characters are the same.
Partition Equal Subset Sum
Given an integer array, determine if it can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Best Time to Buy and Sell Stock with Cooldown
Given an array of stock prices, find the maximum profit with unlimited transactions but a mandatory one-day cooldown after each sell.
Sum of Subarray Minimums
Given an array of integers, find the sum of the minimum value of every contiguous subarray, modulo 10^9 + 7.
Target Sum
Given an integer array and a target, assign '+' or '-' to each element and count the number of ways to achieve the target sum.
Triangle
Given a triangle array, return the minimum path sum from top to bottom, where at each step you may move to an adjacent number on the row below.
Unique Paths II
Given an m x n grid with obstacles, count the number of unique paths from the top-left corner to the bottom-right corner, moving only right or down.
Unique Paths
Given an m x n grid, find the number of unique paths from the top-left corner to the bottom-right corner, moving only right or down.
Valid Parenthesis String
Given a string containing '(', ')' and '*' characters, determine if the string can be valid by treating each '*' as either '(', ')', or an empty string.
Word Break
Given a string and a dictionary of words, determine if the string can be segmented into a space-separated sequence of dictionary words.
Question Banks
Dynamic Programming Warm-Up
Memoization, tabulation, and writing transitions for classic 1D DP. Code stems are Python.
Knapsack Family Quiz
0/1, unbounded, and bounded knapsack: state definitions, loop directions, and which variant fits a given problem.
DP on Strings Quiz
Edit distance, longest common subsequence, and palindrome DP. Drills focus on state definitions and transitions.
DP on Grids Quiz
Path counts, minimum path sum, and obstacle handling on rectangular grids. Code stems are Python.
Interval and State-Machine DP
Interval DP (matrix chain, burst balloons shape) and state-machine DP (stock trading variants). Code stems are Python.
Bitmask DP Essentials
Subset-state DP for TSP-style problems and assignment. Drills cover state encoding, transitions, and the precondition on `n`.
Community
Stone Game
Decide whether the first player wins a take-from-either-end stone game on an even-length pile, with both players playing optimally.
Paint House III
Find the minimum cost to paint exactly target neighborhoods of n houses with k colors, using 3D DP over (index, last color, neighborhoods so far).
Word Break II
Return every sentence that can be formed by space-segmenting a string into dictionary words, using memoized DFS keyed by start index.
Dungeon Game
Find the minimum starting health a knight needs to traverse a dungeon grid from top-left to bottom-right, using REVERSE bottom-up DP from the princess cell.
Cherry Pickup
Maximize cherries collected by walking from top-left to bottom-right and back, modeled as two simultaneous forward walks with shared cells counted once.
Dynamic Programming Patterns
A 5-step framework that turns DP from magic into a checklist, the six recurring patterns, and the memoization-vs-tabulation decision that hides every space optimization.
Minimum Falling Path Sum
Find the minimum sum of a top-to-bottom path in a square matrix where each step moves to one of three cells directly below, using row-by-row DP.
Greedy vs DP: When Can You Actually Be Greedy?
The honest heuristic for proving a greedy choice is safe: exchange argument or matroid structure. Coin change, interval scheduling, and the activity-selection problem worked through.
Wildcard Matching
Match a string against a wildcard pattern with `?` (any single char) and `*` (any sequence) using O(m*n) 2D DP.
Delete and Earn
Maximize total points earned by picking values, where picking value v deletes v-1 and v+1, by reducing to House Robber on a frequency line.
Bitmask DP: The Trick for Subset Problems
Encoding subsets as integers, iterating subsets in O(2^n), and the TSP example that demonstrates the 2^n * n^2 state space. When n is at most 20, bitmask DP is a cheat code.
The DP Problem That Almost Ended My Interview
The interviewer dropped a DP problem at minute four. By minute thirty I had three broken solutions on screen. A postmortem on the round that ended in a no-hire.
DP Questions I Saw Coming and Still Missed
Four DP problems I recognized in the interview and still got wrong. Coin change with the wrong order of loops, LIS in O(n^2), edit distance with a missing base case, and a 2D grid DP with overcounted moves.
