Sub topic 14
Hirschberg's Algorithm: Linear Space with Full Reconstruction
This chapter assumes you know the two-row LCS table from earlier chapters. It also assumes you understand why throwing away rows makes backtracking impossible, which is the reconstruction trade-off. You should be comfortable with recursion and with Big-O space analysis.
The problem it solves
Two rows give you the length of the longest common subsequence (LCS) in O(min(m, n)) space. To recover the subsequence itself, the usual method keeps the full m × n table and walks back from the corner. For two strings of 100,000 characters, that table holds 10^10 cells, which is far too many to store. Hirschberg's algorithm recovers the actual LCS in O(m + n) space and roughly doubles the running time, which stays O(mn).
The key idea: find one crossing point
An optimal LCS path runs through the table from the top-left corner to the bottom-right corner. Split x at its middle row, mid. The path must cross that row at some column k. If you know k, the problem breaks into two independent subproblems:
- LCS of
x[:mid]andy[:k] - LCS of
x[mid:]andy[k:]
To find k, run the two-row algorithm twice:
- Forward: compute the last row of LCS lengths for
x[:mid]against every prefix ofy. - Backward: compute the same row for the reversed
x[mid:]against the reversedy. Entryjof this row gives the LCS length ofx[mid:]and the suffix ofywith lengthj.
The best split is the k that maximizes forward[k] + backward[n - k]. That sum equals the length of the best path that crosses the middle row at column k.
Implementation
def lcs_last_row(x, y):
prev = [0] * (len(y) + 1)
for ch in x:
curr = [0] * (len(y) + 1)
for j in range(1, len(y) + 1):
if ch == y[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev
def hirschberg(x, y):
if len(x) == 0 or len(y) == 0:
return ""
if len(x) == 1:
return x if x in y else ""
mid = len(x) // 2
forward = lcs_last_row(x[:mid], y)
backward = lcs_last_row(x[mid:][::-1], y[::-1])
n = len(y)
k = max(range(n + 1), key=lambda j: forward[j] + backward[n - j])
return hirschberg(x[:mid], y[:k]) + hirschberg(x[mid:], y[k:])
print(hirschberg("ABCBDAB", "BDCABA")) # prints a length-4 LCS: BDABCost analysis
| Resource | Full table + backtrack | Hirschberg |
|---|---|---|
| Time | O(mn) | O(mn), about 2× the constant |
| Space | O(mn) | O(m + n) |
| Recursion depth | none | O(log m) |
The time bound holds because each recursion level splits y into disjoint pieces. Level d therefore does about mn / 2^d work, and the geometric series sums to 2mn. The space bound holds because each level needs only O(n) working rows, and they are freed before the recursive calls run.
When to use it
Hirschberg's method works for any alignment-style DP whose recurrence can run both forward and backward, such as LCS, edit distance, and Needleman–Wunsch alignment. Use it when you need the full solution and the full table does not fit in memory. When the table fits comfortably, plain backtracking is simpler and faster.
Exercise
Why does Hirschberg's algorithm compute the backward pass on the reversed strings instead of reusing the forward rows from the full x?
Show answer
The split needs, for each column k, the LCS length of the bottom half x[mid:] against the suffix y[k:]. Forward rows only describe prefixes of y. Running the two-row algorithm on the reversed strings yields suffix LCS lengths in O(n) space, so forward[k] + backward[n-k] gives the best path through column k of the middle row.
Exercise
Adapt the split step for edit distance. What changes in the selection of k?
Show answer
Edit distance minimizes instead of maximizing, so choose k to minimize forward[k] + backward[n-k]. Here forward and backward are the last rows of the single-row edit distance computation on x[:mid] vs y and on reversed x[mid:] vs reversed y. The base cases also change: when x is empty, insert all of y, and when x has one character, align it against y directly.