Dynamic Programming21 sections · 916 units
Open in Course

Challenge: LCS Space Optimization

Reducing memory

The LCS table uses O(mn)O(mn) space. Can we do better if we only need the length? Yes! Each row only depends on the previous row. Keep two rows: prevprev and currcurr. Swap after each row. Space: O(min(m,n))O(\min(m, n)) by making the shorter string the column dimension. Tradeoff: we lose reconstruction.

To reconstruct with O(n)O(n) space, use Hirschberg's algorithm (divide and conquer on the strings). Hirschberg combines divide-and-conquer with the space reduction to get both O(n)O(n) space and reconstruction.