Classic hard dynamic programming
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Classic hard dynamic programming problems frequently appear in high-bar interviews. We start by seeing why straightforward recursion is slow before applying state inversion and dimension reduction.
The Egg Dropping Puzzle and Brute Force Recursion
The egg dropping puzzle asks for the minimum number of drops needed, in the worst case, to find the critical threshold floor of an n-floor building when you have k eggs.
int solve(int k, int n) { if (n <= 1 || k == 1) return n; // 0 or 1 floor, or one egg left int best = Integer.MAX_VALUE; for (int x = 1; x <= n; x++) { // try dropping from floor x int breaks = solve(k - 1, x - 1); // search the floors below int survives = solve(k, n - x); // search the floors above best = Math.min(best, 1 + Math.max(breaks, survives)); } return best;}With plain recursion, dropping from floor x gives two outcomes: if it breaks, you have k - 1 eggs and test x - 1 lower floors; if it survives, you have k eggs and test n - x upper floors.
Taking the worst case yields 1 + Math.max(solve(k - 1, x - 1), solve(k, n - x)). Testing every floor x from 1 to n takes O(k * n^2) time. For n = 10,000 floors, n^2 is 100 million operations, which is too slow for large inputs.
Inverting the DP State: Moves Formulation
To accelerate egg dropping dramatically, we invert the question: given m moves and k eggs, what is the maximum number of floors we can test?
Example 1 · Egg drop by trying every floor, brute force: exponential time, O(n) space
public class EggBruteDemo { static int moves(int eggs, int floors) { if (floors <= 1) return floors; if (eggs == 1) return floors; int best = floors; for (int x = 1; x <= floors; x++) { // try dropping from floor x int worst = 1 + Math.max(moves(eggs - 1, x - 1), // egg breaks moves(eggs, floors - x)); // egg survives best = Math.min(best, worst); } return best; }
public static void main(String[] args) { System.out.println("Moves for 2 eggs, 6 floors: " + moves(2, 6)); System.out.println("Moves for 3 eggs, 14 floors: " + moves(3, 14)); }}Moves for 2 eggs, 6 floors: 3 Moves for 3 eggs, 14 floors: 4
What this code does
- moves(eggs, floors) tries each floor x and takes the worse of the two outcomes: the egg breaks or survives.
- The same (eggs, floors) pair is solved again and again in different branches.
- The answers 3 and 4 are correct, but the running time grows exponentially with the number of floors.
Example 2 · Egg drop with a floor table, better: O(k · n²) time, O(k · n) space
public class EggFloorsDpDemo { static int moves(int eggs, int floors) { int[][] dp = new int[eggs + 1][floors + 1]; // dp[e][f] = worst-case drops for (int f = 1; f <= floors; f++) dp[1][f] = f; for (int e = 2; e <= eggs; e++) { for (int f = 1; f <= floors; f++) { dp[e][f] = f; for (int x = 1; x <= f; x++) { int worst = 1 + Math.max(dp[e - 1][x - 1], dp[e][f - x]); dp[e][f] = Math.min(dp[e][f], worst); } } } return dp[eggs][floors]; }
public static void main(String[] args) { System.out.println("Moves for 2 eggs, 6 floors: " + moves(2, 6)); System.out.println("Moves for 3 eggs, 14 floors: " + moves(3, 14)); }}Moves for 2 eggs, 6 floors: 3 Moves for 3 eggs, 14 floors: 4
What this code does
- dp[e][f] is the worst-case number of drops with e eggs and f floors.
- Each cell tries every floor x, using cells already filled for fewer eggs or fewer floors.
- Why faster: each pair is solved once and reused, but the triple loop is still O(k · n²).
Example 3 · Egg drop by counting moves, optimal: O(k · m) time, O(k) space
public class EggDropDemo { public static int superEggDrop(int k, int n) { // dp[m][k] = max floors tested with m moves and k eggs int[] dp = new int[k + 1]; int m = 0;
while (dp[k] < n) { m++; for (int i = k; i >= 1; i--) { dp[i] = dp[i] + dp[i - 1] + 1; } } return m; }
public static void main(String[] args) { System.out.println("Moves for 2 eggs, 6 floors: " + superEggDrop(2, 6)); System.out.println("Moves for 3 eggs, 14 floors: " + superEggDrop(3, 14)); }}Moves for 2 eggs, 6 floors: 3 Moves for 3 eggs, 14 floors: 4
What this code does
- Inverts state: dp[m][k] = dp[m-1][k-1] + dp[m-1][k] + 1.
- Updates 1D array backwards to preserve previous move's state.
- Terminates immediately when dp[k] >= n, running in O(k * m) time.
- Why faster: it flips the question. Instead of asking how many drops n floors need, it asks how many floors m drops can cover, and that number grows fast, so m stays small.
If we drop an egg, it either breaks (testing dp[m - 1][k - 1] floors below) or survives (testing dp[m - 1][k] floors above), plus 1 for the tested floor itself: dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1. We increment moves m until dp[m][k] >= n. Because m grows as roughly log(n) when eggs are available, this reduces complexity to O(k * m) where m <= n, running in microseconds.
Word Wrap and Optimal Text Formatting
In Word Wrap, words must be placed into lines of maximum width W to minimize the badness of extra trailing whitespace.
Example 4 · Word wrap with DP: O(n²) time, O(n) space
import java.util.Arrays;
public class WordWrapDemo { public static int minBadness(int[] words, int w) { int n = words.length; int[] dp = new int[n + 1]; Arrays.fill(dp, 1_000_000_000); dp[n] = 0; // zero cost after last word
for (int i = n - 1; i >= 0; i--) { int lineLen = 0; for (int j = i; j < n; j++) { lineLen += words[j] + (j > i ? 1 : 0); if (lineLen > w) break;
// Last line has 0 penalty int cost = (j == n - 1) ? 0 : (w - lineLen) * (w - lineLen); if (dp[j + 1] + cost < dp[i]) { dp[i] = dp[j + 1] + cost; } } } return dp[0]; }
public static void main(String[] args) { int[] words = {3, 2, 2, 5}; System.out.println("Min badness cost: " + minBadness(words, 6)); }}Min badness cost: 10
What this code does
- Words {3, 2, 2, 5} on width 6 puts [3] on line 1 (cost 9), [2, 2] on line 2 (cost 1), and [5] on line 3 (cost 0).
- Line 1 with [3, 2] leaves line 2 [2] (cost 16) and line 3 [5] (cost 0), giving 16.
- Finds the global optimal line partition with minimum badness 10.
Placing words i through j on a line incurs penalty (W - total_length)^2. Define dp[i] as the minimum badness to format words from index i to the end. The recurrence evaluates dp[i] = Math.min(cost(i, j) + dp[j + 1]) over all j where words i..j fit on the line. The last line has 0 penalty, finding the globally optimal formatting in O(n^2) time.
Russian Doll Envelopes: 2D Dimension Reduction
In Russian Doll Envelopes, envelope (w1, h1) fits inside (w2, h2) only if w1 < w2 AND h1 < h2. Checking all pairs takes O(n^2) time, but one special sort turns the problem into a 1D one (shown after the code).
import java.util.Arrays;
public class EnvelopeSort { public static void main(String[] args) { int[][] env = {{5, 4}, {6, 4}, {6, 7}, {2, 3}}; // width ascending; for equal widths, height descending Arrays.sort(env, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]); System.out.println(Arrays.deepToString(env)); // heights 3, 4, 7, 4 -> LIS 3, 4, 7 = 3 nested envelopes }}[[2, 3], [5, 4], [6, 7], [6, 4]]
We can reduce this 2D problem to 1D: sort envelopes by width ascending, and by height descending for ties!
Because equal widths are sorted with heights descending, picking an increasing subsequence of heights can never pick two envelopes with equal widths. The 2D problem collapses into finding the Longest Increasing Subsequence on heights in O(n log n) time.
Example 5 · Cutting a stick with memoised recursion: O(m³) time, O(m²) space
import java.util.Arrays;
public class MemoCutStickDemo { private static int[][] memo; private static int[] all;
public static int minCost(int n, int[] cuts) { int m = cuts.length; all = new int[m + 2]; for (int i = 0; i < m; i++) all[i + 1] = cuts[i]; all[0] = 0; all[m + 1] = n; Arrays.sort(all);
memo = new int[m + 2][m + 2]; for (int[] row : memo) Arrays.fill(row, -1);
return dfs(0, m + 1); }
private static int dfs(int i, int j) { if (j - i <= 1) return 0; if (memo[i][j] != -1) return memo[i][j];
int minCost = Integer.MAX_VALUE; for (int k = i + 1; k < j; k++) { int cost = dfs(i, k) + dfs(k, j) + (all[j] - all[i]); minCost = Math.min(minCost, cost); }
memo[i][j] = minCost; return minCost; }
public static void main(String[] args) { int[] cuts = {5, 6, 1, 4, 2}; System.out.println("Minimum cut cost: " + minCost(9, cuts)); }}Minimum cut cost: 22
What this code does
- Sorts the cuts and inserts boundary points 0 and stick length 9.
- Recursively splits stick segment [i, j] at intermediate cut k.
- Memoizes results to achieve O(m^3) total operations.
Next step
Check your understanding
10 quick questions