Python 3D Academyবাংলা

Saving memory, and rebuilding the actual answer

🌍 In real life. A tally clerk at a cricket match only needs the last over to work out the running score, so they can throw old score sheets away. But if someone later asks which balls were the boundaries, the clerk with no sheets can't say. DP tables are the same: the answer often needs only the last row or two, but rebuilding how the answer was reached needs more.

The idea in one sentence: when every row reads only the row above, keep just two rows (or even one) and the memory drops from the whole table to one row; to rebuild the actual answer, keep the full table or, for each cell, which earlier cell its value came from, and walk those links back from the answer.

Its words:

  • rolling rows: keep prev (the row above) and cur (the row being filled), then let cur become prev
  • one row, backwards: a 0/1 table can even share one row, if each row is filled from the right, so ok[s − x] still holds the old row's value
  • parent pointer: for each cell, the cell its value came from, like before[i]; following them back rebuilds the answer

Here is the cheapest-walk grid of Lesson 58.1, one column wider, keeping only two rows. Watch the old rows fade as they are thrown away: the cost comes out right, but at the end there is nothing to trace back through:

The same grid with the whole table kept: now the walk back from the corner finds the squares themselves:

Why one row works backwards. In subset sum, ok[s] for the new number needs ok[s − x] from before the number was considered. Going from the biggest s down, ok[s − x] (a smaller index) hasn't been touched yet in this pass. Going upwards it would already include x, and x could be used twice.

Rebuilding with parent pointers. The longest increasing subsequence keeps before[i], the index just before i in its best run. Start at the cell with the largest value and follow before until it runs out, then reverse: that is a real longest run, not just its length.

What it costs, by counting. For two 10,000-letter strings, the full LCS table has about 100,000,000 cells; two rows have 20,002. The time is the same, about 100,000,000 steps either way: rolling saves memory, not time. Parent pointers cost one extra list as long as the table they belong to. In Big-O: LCS stays O(m × n) time, while two rows cut the memory from O(m × n) to O(n).

def lcs_two_rows(a, b):
    prev = [0] * (len(b) + 1)                   # row i - 1 of the full table
    for i in range(1, len(a) + 1):
        cur = [0] * (len(b) + 1)                # row i, a new list each time
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1] + 1
            else:
                cur[j] = max(prev[j], cur[j - 1])
        prev = cur                              # row i becomes "the row above"
    return prev[len(b)]

def can_make(nums, target):
    ok = [True] + [False] * target              # ok[s]: can the numbers so far make s?
    for x in nums:
        for s in range(target, x - 1, -1):      # backwards: ok[s - x] is still last row's
            ok[s] = ok[s] or ok[s - x]
    return ok[target]

def lis_sequence(nums):
    if not nums:
        return []
    dp = [1] * len(nums)
    before = [None] * len(nums)                 # before[i]: the index just before i in its best run
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] < nums[i] and dp[j] + 1 > dp[i]:
                dp[i] = dp[j] + 1
                before[i] = j
    i = dp.index(max(dp))                       # where the best run ends
    run = []
    while i is not None:                        # follow the arrows back
        run.append(nums[i])
        i = before[i]
    return run[::-1]

print(lcs_two_rows("CODE", "COLD"), can_make([3, 1, 4, 2], 5), can_make([3], 6))
print(lis_sequence([9, 1, 8, 2, 7, 3, 6]))

Mistakes and edge cases.

  • prev = cur with no new list: both names then share one list, and the next row overwrites the row it is reading; make a new cur for every row
  • one row, forwards: filling a 0/1 row from the left uses each item many times; go from the right
  • rolling and then tracing back: once old rows are gone, the path is gone too; decide first whether you need it
  • pointers on ties: with dp[j] + 1 > dp[i] the first best j is kept; with >= the last one is, and the rebuilt run can differ, though its length can't

Quiz

  1. When can a DP table keep only two rows?

    • When every row reads only the row above it
    • Always
    • When the table is square
  2. What does this print?

    def can_make(nums, target):
        ok = [True] + [False] * target              # ok[s]: can the numbers so far make s?
        for x in nums:
            for s in range(target, x - 1, -1):      # backwards: ok[s - x] is still last row's
                ok[s] = ok[s] or ok[s - x]
        return ok[target]
    
    print(can_make([3], 6))
  3. What does this print?

    def lis_sequence(nums):
        if not nums:
            return []
        dp = [1] * len(nums)
        before = [None] * len(nums)                 # before[i]: the index just before i in its best run
        for i in range(len(nums)):
            for j in range(i):
                if nums[j] < nums[i] and dp[j] + 1 > dp[i]:
                    dp[i] = dp[j] + 1
                    before[i] = j
        i = dp.index(max(dp))                       # where the best run ends
        run = []
        while i is not None:                        # follow the arrows back
            run.append(nums[i])
            i = before[i]
        return run[::-1]
    
    print(lis_sequence([4, 1, 2, 3]))
  4. Two 10,000-letter strings: what does keeping two LCS rows save?

    • Memory: about 20,000 cells instead of 100,000,000; the time stays the same
    • Time: it becomes twice as fast
    • Nothing
  5. This one-row can_make([3], 6) answers True: one 3 seems to make 6. Which line is wrong?

    def can_make(nums, target):
        ok = [True] + [False] * target
        for x in nums:
            for s in range(x, target + 1):
                ok[s] = ok[s] or ok[s - x]
        return ok[target]

Coding tasks

  1. Write lcs_two_rows(a, b): the length of the longest common subsequence of a and b, keeping only two rows of the table (the row above and the row being filled).

  2. Write lis_sequence(nums): return a longest strictly increasing subsequence itself, as a list. (Every test has only one.)