DP with state compression
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Many DP solutions fill a big table but each row only needs the row just before it. State compression keeps only that one line instead of the whole table, so the answer stays the same while the memory used shrinks from a wall of numbers to a single strip.
Practical use cases
- Web app: Diff or similarity check in the browser. A document editor compares two long versions of a text to show what changed. A full table for two 20,000-character files would be 400 million cells and crash the tab. Keeping only the previous row makes it 20,000 cells, so the comparison runs on a phone without freezing.
- Web app: Budget picker on a shared server. A SaaS plan builder chooses the best add-ons within a customer budget, a knapsack style problem. On a small PHP server running many requests at once, memory is the limit. Reusing one array instead of one per item lets hundreds of users run it at the same time without the server swapping to disk.
- System: Genome and embedded devices. Comparing two long DNA strings or running on a tiny device with little memory only works if the working table is a single row. Nothing about the answer changes, only the scratch space shrinks, so the same program fits on much smaller machines.
The story: The Notebook With One Line
Mira was crossing a town of toll roads laid out like a grid. Starting at the top-left, she could move only right or down, and every square charged a toll. She wanted the cheapest total to the bottom-right corner. Her friend had a notebook with a table as big as the whole town, and for a big town the notebook ran out of pages.
Mira looked at how a cell is filled: it only needs the cell just above and the cell just to the left. Once row 3 is done, row 1 is never looked at again. So why store it? She kept one single line of numbers. When she moved to a new row, each slot still held the answer from the row above, which is exactly the "above" value she needed. She computed the new number and wrote it over the old one. The cell to the left was already overwritten with its new value, so it was also ready.
The answer in the last slot matched the full table: 8. But the memory was one row instead of the whole grid. This trick, throwing away table rows you will never read again, is called state compression (also rolling array or space optimisation). It is how the knapsack lesson turned a 2D table into one strip, and how LCS can use two rows.
How to spot this problem, and where you need it
Your dynamic programming answer is correct but uses so much memory that the server, browser tab or device runs out before it finishes, even though each step only looks at the previous one.
Signs you need it
- Your DP table has two dimensions, and when you look at the formula each cell only uses the row above (or the cell to the left).
- You get "out of memory" or the PHP memory_limit error when the inputs grow, while the time is still acceptable.
- You only want the final number, not the actual path that produced it.
- The table is thousands by thousands but you throw away old rows mentally as you go.
Where to use it in a project
- Text comparison, similarity scoring or spell-suggestion features working on long strings.
- Knapsack-style choosers like budget pickers, cargo loading or plan builders.
- Code that must run in memory-limited places such as phones, browsers or shared hosting.
The solution
Look at your DP formula and see which earlier rows it reads. Usually it is only the previous row. Keep one array (or two) for those rows, compute the new row into it, and overwrite the old values as you go, being careful about the order so you do not overwrite something you still need. This is DP with state compression, also called rolling arrays.
Payoff: Before: a 20,000 by 20,000 table (400 million cells). After: one row of 20,000 cells, about 20,000 times less memory with the same answer.
Explain it like I am 8
You are writing answers on a whiteboard row by row. You notice that to write today's row, you only need yesterday's row. So instead of a new whiteboard every day, you erase and reuse the same line. You keep what you need, and wipe what you will never look at again.
How it works, step by step
- Find out what each cell really needs. Here: the cell above and the cell to the left.
- Keep only that much. One row
dp[0..cols-1]. - Before you overwrite
dp[c]it holds the "above" value;dp[c-1]already holds the new "left" value. - So the update is in place:
dp[c] = grid[r][c] + min(dp[c], dp[c-1]). - Handle the edges (first row, first column) separately. If a cell needs the diagonal too, save the old value in a temporary variable before overwriting.
- The answer is the last slot:
dp[cols-1].
The code in four languages
PHP
<?php
// Cheapest walk from top-left to bottom-right (right/down moves), using ONE row of memory.
function minPathSum(array $grid): int {
$rows = count($grid); $cols = count($grid[0]);
$dp = array_fill(0, $cols, 0); // the single remembered row
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($r === 0 && $c === 0) {
$best = 0;
} elseif ($r === 0) {
$best = $dp[$c - 1]; // first row: only from the left
} elseif ($c === 0) {
$best = $dp[$c]; // first column: only from above
} else {
$best = min($dp[$c], $dp[$c - 1]); // above (old value) or left (new value)
}
$dp[$c] = $best + $grid[$r][$c]; // overwrite in place
}
}
return $dp[$cols - 1];
}
// The same with a full 2D table, to prove both give the same answer
function minPathSumFull(array $grid): int {
$rows = count($grid); $cols = count($grid[0]);
$t = [];
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($r === 0 && $c === 0) $b = 0;
elseif ($r === 0) $b = $t[$r][$c - 1];
elseif ($c === 0) $b = $t[$r - 1][$c];
else $b = min($t[$r - 1][$c], $t[$r][$c - 1]);
$t[$r][$c] = $b + $grid[$r][$c];
}
}
return $t[$rows - 1][$cols - 1];
}
$grid = [[1, 3, 1, 2], [1, 5, 1, 3], [4, 2, 1, 1]];
echo minPathSum($grid), ' ', minPathSumFull($grid), "\n"; // 8 8JavaScript
// Cheapest walk from top-left to bottom-right (right/down moves), using ONE row of memory.
function minPathSum(grid) {
const rows = grid.length, cols = grid[0].length;
const dp = new Array(cols).fill(0); // the single remembered row
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let best;
if (r === 0 && c === 0) best = 0;
else if (r === 0) best = dp[c - 1]; // first row: only from the left
else if (c === 0) best = dp[c]; // first column: only from above
else best = Math.min(dp[c], dp[c - 1]); // above (old value) or left (new value)
dp[c] = best + grid[r][c]; // overwrite in place
}
}
return dp[cols - 1];
}
// The same with a full 2D table, to prove both give the same answer
function minPathSumFull(grid) {
const rows = grid.length, cols = grid[0].length;
const t = Array.from({ length: rows }, () => new Array(cols).fill(0));
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
let b;
if (r === 0 && c === 0) b = 0;
else if (r === 0) b = t[r][c - 1];
else if (c === 0) b = t[r - 1][c];
else b = Math.min(t[r - 1][c], t[r][c - 1]);
t[r][c] = b + grid[r][c];
}
}
return t[rows - 1][cols - 1];
}
const grid = [[1, 3, 1, 2], [1, 5, 1, 3], [4, 2, 1, 1]];
console.log(minPathSum(grid) + ' ' + minPathSumFull(grid)); // 8 8Java
public class Main {
// Cheapest walk from top-left to bottom-right (right/down moves), using ONE row of memory.
static int minPathSum(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
int[] dp = new int[cols]; // the single remembered row
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int best;
if (r == 0 && c == 0) best = 0;
else if (r == 0) best = dp[c - 1]; // first row: only from the left
else if (c == 0) best = dp[c]; // first column: only from above
else best = Math.min(dp[c], dp[c - 1]); // above (old value) or left (new value)
dp[c] = best + grid[r][c]; // overwrite in place
}
}
return dp[cols - 1];
}
// The same with a full 2D table, to prove both give the same answer
static int minPathSumFull(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
int[][] t = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int b;
if (r == 0 && c == 0) b = 0;
else if (r == 0) b = t[r][c - 1];
else if (c == 0) b = t[r - 1][c];
else b = Math.min(t[r - 1][c], t[r][c - 1]);
t[r][c] = b + grid[r][c];
}
}
return t[rows - 1][cols - 1];
}
public static void main(String[] args) {
int[][] grid = {{1, 3, 1, 2}, {1, 5, 1, 3}, {4, 2, 1, 1}};
System.out.println(minPathSum(grid) + " " + minPathSumFull(grid)); // 8 8
}
}Go
package main
import "fmt"
// minPathSum finds the cheapest walk from top-left to bottom-right
// (right/down moves), using ONE row of memory.
func minPathSum(grid [][]int) int {
rows, cols := len(grid), len(grid[0])
dp := make([]int, cols) // the single remembered row
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
var best int
switch {
case r == 0 && c == 0:
best = 0
case r == 0:
best = dp[c-1] // first row: only from the left
case c == 0:
best = dp[c] // first column: only from above
default:
best = min(dp[c], dp[c-1]) // above (old value) or left (new value)
}
dp[c] = best + grid[r][c] // overwrite in place
}
}
return dp[cols-1]
}
// minPathSumFull does the same with a full 2D table, to prove both give the same answer.
func minPathSumFull(grid [][]int) int {
rows, cols := len(grid), len(grid[0])
t := make([][]int, rows)
for r := range t {
t[r] = make([]int, cols)
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
var b int
switch {
case r == 0 && c == 0:
b = 0
case r == 0:
b = t[r][c-1]
case c == 0:
b = t[r-1][c]
default:
b = min(t[r-1][c], t[r][c-1])
}
t[r][c] = b + grid[r][c]
}
}
return t[rows-1][cols-1]
}
func main() {
grid := [][]int{{1, 3, 1, 2}, {1, 5, 1, 3}, {4, 2, 1, 1}}
fmt.Println(minPathSum(grid), minPathSumFull(grid)) // 8 8
}Time: O(rows × cols) · Extra space: O(cols). The time stays the same; the memory drops from a whole table to a single row.
Watch out for
- Overwriting a value you still need. If a cell also needs the diagonal, save it in a temporary variable first.
- Compressing when you must rebuild the actual path afterwards: the discarded rows are exactly what the path rebuild needs.
- Walking the row in the wrong direction. Left to right here (left needs new values); in 0/1 knapsack it must be right to left.
Quick check
- Why can we throw away old rows?
- They are always zero
- Later cells only look at the previous row and the current row
- The table is too big
- What does dp[c] hold just before we overwrite it?
- The old value from the row above
- Zero
- The left value
- What changes after state compression?
- Time drops from O(rows × cols) to O(cols)
- Memory drops, time stays the same
- The answer gets approximate