Sub topic 15
Hirschberg's Algorithm: Reconstruction in Linear Space
This chapter assumes you already know the bottom-up LCS table, the traceback that recovers a subsequence from it, and the two-row pass that computes the LCS length in O(min(m, n)) space. You should also be comfortable reading recursive Python and doing Big-O arithmetic.
The Problem Two Rows Leave Open
The two-row method gives you the length of the LCS in linear space. It does not give you the subsequence itself. Traceback walks backward through the full table, and the two-row method throws earlier rows away. For two sequences of 100,000 items each, the full table holds 10^10 cells. That is too large for memory, even though computing it takes only a few minutes.
Dan Hirschberg published a fix in 1975. His method recovers an actual LCS in O(mn) time and O(m + n) space. It costs about twice as much time as the plain table. It spends that extra time recomputing rows so that it never has to store them.
The Key Idea: Find One Point on the Path
Picture the optimal traceback path through the full table. It starts at cell (0, 0) and ends at cell (m, n). The path must cross the middle row, i = mid, at some column k. If you knew k, the problem would split into two independent pieces:
- an LCS of
a[:mid]andb[:k] - an LCS of
a[mid:]andb[k:]
Joining the two answers gives an LCS of the whole input. Each piece is smaller, so you recurse.
The work is all in finding k without the full table. Two two-row passes do it:
- A forward pass over
a[:mid]againstb. Its last row givesleft[j] = LCS(a[:mid], b[:j])for everyj. - A reverse pass over
a[mid:]reversed, againstbreversed. Its last row givesright[j] = LCS(a[mid:], b[n-j:]). An LCS of two reversed strings is the reverse of an LCS of the originals, so their lengths are equal.
For each candidate split k, left[k] + right[n - k] is the best total length you can get if the path crosses the middle row at column k. Pick the k that maximizes this sum. That maximum equals the full LCS length, because every LCS crosses the middle row somewhere.
The Reference Implementation
def _last_row(a, b):
prev = [0] * (len(b) + 1)
for x in a:
curr = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
curr[j] = prev[j - 1] + 1 if x == y else max(prev[j], curr[j - 1])
prev = curr
return prev
def hirschberg(a, b):
if not a or not b:
return ""
if len(a) == 1:
return a if a in b else ""
mid = len(a) // 2
left = _last_row(a[:mid], b)
right = _last_row(a[mid:][::-1], b[::-1])
n = len(b)
k = max(range(n + 1), key=lambda j: left[j] + right[n - j])
return hirschberg(a[:mid], b[:k]) + hirschberg(a[mid:], b[k:])
result = hirschberg("ABCBDAB", "BDCABA")
print(result, len(result)) # BDAB 4There are two base cases. An empty input has an empty LCS. A single-character a matches at most one character, so the answer is that character if it appears in b, and empty otherwise.
Tracing the Running Example
Take a = "ABCBDAB" and b = "BDCABA". Then mid = 3, which splits a into "ABC" and "BDAB".
| k | left[k] = LCS("ABC", b[:k]) | right[6-k] = LCS("BDAB", b[k:]) | Sum |
|---|---|---|---|
| 0 | 0 | 4 | 4 |
| 1 | 1 | 3 | 4 |
| 2 | 1 | 2 | 3 |
| 3 | 2 | 2 | 4 |
| 4 | 2 | 2 | 4 |
| 5 | 2 | 1 | 3 |
| 6 | 2 | 0 | 2 |
The maximum is 4, which matches the known LCS length. Python's max returns the first maximizing k, which is 0. The left half contributes nothing, and the right call solves "BDAB" against all of "BDCABA".
Reading the leaves from left to right gives "BDAB".
Complexity Analysis
Time. At the top level, the two passes together touch mid * n + (m - mid) * n = mn cells. At the next level, the subproblems have sizes (m/2) × k and (m/2) × (n - k), so they total mn/2 cells no matter which k was chosen. Each level does half the work of the level above it:
mn + mn/2 + mn/4 + ... ≤ 2mn
The total is O(mn). In practice the constant is about twice that of the full-table method.
Space. Each pass needs O(n) for its rows. The recursion depth is about log₂ m, because a halves at every level. An implementation that passes index bounds uses O(m + n) in total: the output plus a constant amount per stack frame.
Gotchas in the Reference Version
Slicing Breaks the Linear-Space Claim
a[:mid], b[:k], and b[::-1] each make a copy. The copies of b along one recursion path can each be close to length n, so live memory can grow to O(n log m). That is still far smaller than O(mn), but it is not strictly linear.
The Base Case Only Works for Strings
a in b tests for a substring when the inputs are str. When they are lists, [x] in b asks whether the list [x] is an element of b. That is almost always false. For diffing lists of lines, you would test a[0] in b.
Tie-Breaking Differs from Table Traceback
When several split columns tie, the first maximum wins. That rule picks a valid LCS, but it may be a different LCS from the one your table traceback returns. The table traceback returned one answer for this example, and Hirschberg returns "BDAB". Both are correct. Tests should check the length and the subsequence property, not one exact string.
An Index-Based Version for Any Sequence
This version passes bounds instead of slices and works on strings, lists, or tuples. It also checks itself against the full table on random inputs.
import random
def lcs_hirschberg(a, b):
out = []
def last_row(i0, i1, j0, j1, reverse):
width = j1 - j0
prev = [0] * (width + 1)
rows = range(i1 - 1, i0 - 1, -1) if reverse else range(i0, i1)
for i in rows:
x = a[i]
curr = [0] * (width + 1)
for t in range(1, width + 1):
y = b[j1 - t] if reverse else b[j0 + t - 1]
curr[t] = prev[t - 1] + 1 if x == y else max(prev[t], curr[t - 1])
prev = curr
return prev
def solve(i0, i1, j0, j1):
if i0 >= i1 or j0 >= j1:
return
if i1 - i0 == 1:
for j in range(j0, j1):
if b[j] == a[i0]:
out.append(a[i0])
return
return
mid = (i0 + i1) // 2
left = last_row(i0, mid, j0, j1, False)
right = last_row(mid, i1, j0, j1, True)
width = j1 - j0
k = max(range(width + 1), key=lambda t: left[t] + right[width - t])
solve(i0, mid, j0, j0 + k)
solve(mid, i1, j0 + k, j1)
solve(0, len(a), 0, len(b))
return out
def full_table_length(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
def is_subsequence(s, t):
it = iter(t)
return all(any(x == y for y in it) for x in s)
print(lcs_hirschberg(list("ABCBDAB"), list("BDCABA"))) # ['B', 'D', 'A', 'B']
for _ in range(500):
a = [random.choice("ABC") for _ in range(random.randint(0, 12))]
b = [random.choice("ABC") for _ in range(random.randint(0, 12))]
s = lcs_hirschberg(a, b)
assert len(s) == full_table_length(a, b)
assert is_subsequence(s, a) and is_subsequence(s, b)
print("all checks passed")When to Use Hirschberg
| Situation | Best choice |
|---|---|
| Inputs small enough that an (m+1)×(n+1) table fits in memory | Full table plus traceback. It is simpler and about 2× faster. |
| Only the length is needed | Two-row pass |
| Subsequence needed and the table does not fit | Hirschberg |
| Very long, very similar inputs (typical diffs) | Output-sensitive algorithms such as Myers' O((m+n)D) diff, often combined with a Hirschberg-style midpoint split |
Exercise
Why does max over k of left[k] + right[n - k] equal the full LCS length, rather than overestimating it?
Show answer
Every pair of subsequences, one common to a[:mid] and b[:k] and one common to a[mid:] and b[k:], joins into a common subsequence of a and b, so no sum can exceed the LCS length. Every LCS crosses the boundary between a[:mid] and a[mid:] at some column k, and its two parts have lengths at most left[k] and right[n - k]. So some sum reaches the LCS length.
Exercise
The reference hirschberg function is called with lists of lines, a = ["x"] and b = ["w", "x"]. What does it return, and why?
Show answer
It returns "" (an empty string). With len(a) == 1, the test a in b asks whether the list ["x"] is an element of b, which is false. The fix is to test a[0] in b and return a list, so the result type matches the input.
Exercise
Show that the second recursion level costs mn/2 cells regardless of the split column k chosen at the top level.
Show answer
The two subproblems are (m/2) × k and (m/2) × (n - k). Their cell counts sum to (m/2)(k + n - k) = mn/2. Each further level halves again, so the total is at most 2mn.