Sub topic 15
Hirschberg's Algorithm: Reconstruction in Linear Space
This chapter assumes you already know the bottom-up LCS table, the traceback that reads an LCS out of it, and the two-row method that computes only the length. Those methods leave you with a choice. The full table lets you recover the subsequence but needs O(mn) memory. The two-row pass uses O(min(m, n)) memory but gives only a number. Hirschberg's algorithm recovers an actual LCS in O(mn) time while keeping the working space linear.
The Key Idea: Find the Split Point
Split the first string a at its midpoint into a[:mid] and a[mid:]. Some optimal LCS of a and b uses one prefix b[:k] with the left half and the remaining suffix b[k:] with the right half. If you know k, you can solve two smaller, independent problems and join their answers.
Two-row passes can find k:
- A forward pass computes the last row for
a[:mid]againstb. Entryleft[j]is the LCS length ofa[:mid]andb[:j]. - A reverse pass runs the same routine on the reversed
a[mid:]and the reversedb. Entryright[j]is the LCS length ofa[mid:]and the lastjcharacters ofb. - Choose the
kthat maximizesleft[k] + right[n - k]. That sum is the best LCS length you can get whenbis cut at positionk.
Neither pass keeps more than two rows, so finding the split costs linear space.
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)) # one LCS of length 4The base cases do all the real matching. An empty string contributes nothing. A single character either occurs in b or it does not.
Cost Analysis
| Resource | Full-table traceback | Hirschberg |
|---|---|---|
| Time | O(mn) | O(mn), about 2× the work |
| Working space | O(mn) | O(m + n) |
| Recursion depth | none (iterative) | O(log m) |
The time stays O(mn) because the total work shrinks at each level. The top level does about mn cell updates. The next level works on halves of a against pieces of b whose lengths add up to n, so it does about mn/2. The series mn + mn/2 + mn/4 + … stays below 2mn.
Where It Matters
Hirschberg's method is worth the extra constant factor when m × n cells will not fit in memory. Aligning long DNA sequences or diffing very large files are typical cases. For short inputs, the plain table with traceback is simpler and faster.
Exercise
Why does Hirschberg's algorithm take roughly twice as long as a single full-table fill, and not O(mn log m)?
Show answer
At each recursion level the subproblems split a into halves while their pieces of b add up to at most n, so level d does about mn / 2^d work. Summing mn + mn/2 + mn/4 + ... gives less than 2mn, which is still O(mn).
Exercise
Hirschberg's algorithm picks k with left[k] + right[n - k]. What value should that maximum equal at the top level?
Show answer
It equals the LCS length of the full strings a and b. Every common subsequence divides at some cut of b, and the best cut gives the optimal total.