Sub topic 14
Hirschberg's Algorithm: Linear Space with Full Reconstruction
The previous chapter showed the usual trade-off. If you keep only two rows of the longest common subsequence (LCS) table, you get the length of the LCS in O(min(m, n)) space, but you lose the backtracking path that spells out the subsequence itself. Hirschberg's algorithm removes that trade-off. It returns the full LCS in linear space and still runs in O(mn) time. The cost is roughly double the arithmetic and some recursion.
This chapter assumes you know the two-row LCS code from earlier chapters, the standard LCS recurrence, basic recursion, and Big-O analysis.
The Core Idea: Find One Cell on the Optimal Path
Think of the full LCS table as a grid with x on the rows and y on the columns. Backtracking walks a path from cell (m, n) to (0, 0). Any monotone path through this grid must cross the middle row, i = mid, at some column k. If you can find a k where an optimal path crosses that row, the problem splits into two independent subproblems:
- LCS of
x[:mid]andy[:k] - LCS of
x[mid:]andy[k:]
The full answer is the first result joined to the second. Each subproblem is again an LCS problem, so you recurse on both.
Finding k without storing the grid is the clever part. It takes two linear-space passes.
The Forward Pass
Run the two-row LCS on x[:mid] against all of y. The final row is left, where left[k] is the LCS length of x[:mid] and y[:k], for every k from 0 to n.
The Backward Pass
Run the same two-row code on the reversed strings: x[mid:] reversed against y reversed. A prefix of reversed y with length n - k is y[k:] read backwards, and reversing both strings does not change the LCS length. So right[n - k] is the LCS length of x[mid:] and y[k:].
Choosing the Split
An optimal LCS of the whole problem has length
max over k of left[k] + right[n - k]
and any k that reaches this maximum is a valid split point. The equation holds because every common subsequence splits into a part matched inside x[:mid] and a part matched inside x[mid:], and the columns used by the first part all come before the columns used by the second.
A Complete Implementation
def lcs_last_row(x, y):
"""Return the final row of the LCS table for x against y, in O(len(y)) space."""
prev = [0] * (len(y) + 1)
for i in range(1, len(x) + 1):
curr = [0] * (len(y) + 1)
for j in range(1, len(y) + 1):
if x[i - 1] == 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):
"""Return one longest common subsequence of strings x and 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
n = len(y)
left = lcs_last_row(x[:mid], y)
right = lcs_last_row(x[mid:][::-1], y[::-1])
best_k = max(range(n + 1), key=lambda k: left[k] + right[n - k])
return hirschberg(x[:mid], y[:best_k]) + hirschberg(x[mid:], y[best_k:])
if __name__ == "__main__":
print(hirschberg("ABCBDAB", "BDCABA")) # BDAB (length 4)
print(hirschberg("AGGTAB", "GXTXAYB")) # GTAB
print(hirschberg("", "ABC")) # empty stringThe base cases matter. With an empty string the LCS is empty. With one character in x, the LCS is that character if it appears anywhere in y and empty otherwise. Without the one-character case, mid would be 0 and the recursion would call itself on the same input forever.
Worked Example
Take x = "ABCBDAB" and y = "BDCABA", so m = 7, n = 6, and mid = 3. The top half is "ABC" and the bottom half is "BDAB".
| k | y[:k] | left[k] | y[k:] | right[n-k] | sum |
|---|---|---|---|---|---|
| 0 | "" | 0 | BDCABA | 4 | 4 |
| 1 | B | 1 | DCABA | 3 | 4 |
| 2 | BD | 1 | CABA | 2 | 3 |
| 3 | BDC | 2 | ABA | 2 | 4 |
| 4 | BDCA | 2 | BA | 2 | 4 |
| 5 | BDCAB | 2 | A | 1 | 3 |
| 6 | BDCABA | 2 | "" | 0 | 2 |
The maximum is 4, which matches the known LCS length. Several columns tie. Python's max returns the first, k = 0, so the recursion calls hirschberg("ABC", ""), which returns "", and hirschberg("BDAB", "BDCABA"), which returns "BDAB". A split at k = 3 would also be correct and would lead to a different LCS of the same length, such as "BCBA". Ties mean several optimal paths exist. Any tied column lies on at least one of them.
Why the Time Stays O(mn)
Each call on a subproblem of size a × b does about a·b cell updates across its two passes. The two children have sizes (a/2) × k and (a/2) × (b - k), so together they cover a·b/2 cells, whatever k is. The total work forms a geometric series:
mn + mn/2 + mn/4 + ... ≤ 2mn
The constant doubles compared with the plain table, but the asymptotic time does not change. The split column k only decides how the cells are shared between the two children, never how many there are.
Where the Memory Goes
| Component | Space |
|---|---|
| `left` and `right` rows plus the working row | O(n) |
| Recursion stack | O(log m) frames |
| Output string | O(min(m, n)) |
| Full table (avoided) | O(mn) |
The rows are freed before the recursive calls return their results, so only one level's rows exist at a time if you drop left and right before recursing. In CPython, local variables survive until the frame ends, so each frame on the stack keeps its rows alive. Each level's rows are at most n + 1 long, and there are O(log m) levels, so the worst case is O(n log m). Adding del left, right before the recursive calls brings the peak back to O(n).
Gotchas and Failure Modes
- Off-by-one in the backward lookup.
rightis indexed by the length of the reversed suffix, so the pairing isleft[k] + right[n - k]. Writingright[k]instead silently returns wrong splits and still produces a common subsequence, just not a longest one. - Missing base case. If
len(x) == 1is not handled,mid = 0and the call repeats forever. - Non-string sequences.
x in ytests for a substring on strings. For lists, usex[0] in yand return[x[0]], and replace""with[]. - Recursion limit. The depth is about log₂ m, so it stays small. A depth problem points to a split bug, not to large input.
Beyond LCS
The same pattern works for any alignment-style DP whose optimal path is monotone through a grid and whose cost adds up along the path. Global sequence alignment (Needleman–Wunsch) and edit distance with operation recovery are the standard cases. In the alignment versions you minimize forward[k] + backward[n - k] for costs instead of maximizing for matches, and the base cases produce explicit insert and delete operations instead of an empty string.
Hirschberg's method is the right choice when you need the actual solution, the table would not fit in memory, and paying about twice the time is acceptable. If the table fits, plain backtracking is simpler and faster. If you need only the optimal value, two rows are enough and the recursion adds nothing.
Exercise
In the worked example, the split k = 3 also reaches the maximum sum of 4. Which two subproblems would the recursion solve for k = 3, and which LCS length must each return?
Show answer
It would solve hirschberg("ABC", "BDC") and hirschberg("BDAB", "ABA"). From the table, left[3] = 2 and right[3] = 2, so each must return a subsequence of length 2, for example "BC" and "AB", giving "BCAB" of total length 4.
Exercise
A colleague says the recursion makes Hirschberg's algorithm O(mn log m) time because there are log m levels and each does O(mn) work. What is wrong with this argument?
Show answer
Each level does not do O(mn) work. The children of a subproblem of size a × b together cover only a·b/2 cells, because both have height a/2 and their widths add up to b. The work per level halves, so the total is at most mn(1 + 1/2 + 1/4 + ...) ≤ 2mn, which is O(mn).
Exercise
You must recover an LCS of a 2,000,000-character string and a 5,000-character string. Which string should be x (the one halved by the recursion), and what is the working space of the rows?
Show answer
Make the 2,000,000-character string x and the 5,000-character string y. The rows then have 5,001 entries, so the working space is O(5,000) (times O(log m) if frames keep their rows alive), and the recursion depth is about log₂ 2,000,000 ≈ 21.