Keeping only the last few states

Video lessonComing soon

1 Most of the table is never read again

The last lesson filled a table for the robber's street. The five houses hold 3, 8, 4, 2 and 6 thousand rupees, and best[i] is the most money from the first i houses:

3081422364
nums
00318283104145
best: the answer is best[5] = 14

Each slot came from the same line:

best[i] = max(best[i − 1], best[i − 2] + nums[i − 1])

That line reads only two slots. To work out best[5], it needs best[4] and best[3]. It never looks at best[0], best[1] or best[2] again. Those slots were needed once, and then they sit in memory until the end.

The table is a strip of paper, and the loop reads it through a window two slots wide. The window slides one slot to the right at each house. Everything to the left of it is dead weight. This lesson throws the dead part away and keeps only the window.

2 Only two slots are alive

Here is the end of the fill again. The orange slots are the window, the blue slot is the one being written, and the faded slots will never be read again:

The window slides along best
3081422364
nums: house 2
0031828345
best[3] = max(8, 3 + 4) = 8. best[0] is done

At every step, two slots are read and one is written. The faded part grows by one slot each time. With n houses, the table holds n + 1 numbers, but only two of them matter at any moment.

So we replace the table with two variables:

  • prev1 holds best[i - 1]. Skipping house i − 1 gives this much.
  • prev2 holds best[i - 2]. Taking house i − 1 adds its money to this.

They start as the two base cases, best[0] = 0 and best[1] = nums[0]. Every street has at least one house, so both always exist.

3 Compute first, then shift

At each i, the window does three things, in this order:

  1. Work out current = max(prev1, prev2 + nums[i - 1]).
  2. Move prev1 into prev2. The old prev2 falls out of the window.
  3. Move current into prev1.

Here is i = 5, the last house, which holds 6:

best[5] in three moves
3081422364
nums: house 4
8prev210prev114current
current = max(10, 8 + 6) = 14

The order matters. If we shift first, prev2 already holds the new value when the formula reads it. The mistakes section shows what that breaks.

The whole street, with each variable's value when the loop reaches i:

inums[i − 1]prev2prev1current
2803max(3, 0 + 8) = 8
3438max(8, 3 + 4) = 8
4288max(8, 8 + 2) = 10
56810max(10, 8 + 6) = 14

The current column is the table from the last lesson: 8, 8, 10, 14. Each row's prev1 is the row above's current, and its prev2 is the row above's prev1. After the loop, prev1 holds 14.

4 The code

The table code from the last lesson changes in two places. The two base cases go into prev2 and prev1, and the loop ends with the shift:

C++

Keep all three long long. 10⁵ houses of 10⁹ each can add up to 5 × 10¹³, far more than an int holds. max also needs both arguments of the same type.

Keep all three long. 10⁵ houses of 10⁹ each can add up to 5 × 10¹³, far more than an int holds.

One line also works. prev2, prev1 = prev1, current works out the right side before it assigns anything, so the order cannot go wrong.

Numbers are safe here. They stay exact up to about 9 × 10¹⁵, and the largest total is about 5 × 10¹³.

Convert each value. int64(nums[i-1]) is needed because Go never mixes int and int64 in one sum.

Convert before adding. nums[i - 1] as i64 keeps the sum from overflowing an i32 past 2 × 10⁹.

Keep all three long. 10⁵ houses of 10⁹ each can add up to 5 × 10¹³, far more than an int holds.

Every tab returns 14 on [3, 8, 4, 2, 6] and 7 on [7]. With one house, the loop never runs, and prev1 already holds nums[0].

5 What it saves, and what it does not

The loop still visits every house once and does a fixed amount of work at each. Time stays O(n). Space drops from O(n) for the table to O(1) for a few variables.

This is a memory saving, not a speed-up. At n = 10⁵, a table of 64-bit numbers takes about 800 KB, which is small. At n = 10⁷, it takes about 80 MB, while two variables take 16 bytes. Interviewers often ask for it as the follow-up to the table version: "can you do it in less space?"

6 What we lose: the choices

The table holds more than the answer. It also tells us which houses were robbed, and we can read them back by walking from the end. At each i, we compare best[i] with best[i - 1]:

  • They are equal. Skipping house i − 1 was enough, so it was skipped. Move to i − 1.
  • best[i] is bigger. House i − 1 was robbed, so its neighbour, house i − 2, was not. Move to i − 2.
Walking back through best
00318283104145i
best
3081422364
14 is more than 10: house 4 robbed

The walk stops at i = 0, with houses 1 and 4: 8 + 6 = 14. In pseudocode:

i = n
while i >= 1:
    if best[i] == best[i - 1]:
        i = i - 1        // house i - 1 was skipped
    else:
        add house i - 1 to the plan
        i = i - 2        // house i - 2 cannot be robbed

The two-variable version cannot do this. By the end, best[0] to best[3] are gone. So when a problem asks for the choices themselves, keep the full table.

7 Keeping k states, and rows

The window can be wider than two. When each answer reads the last k answers, we keep k values. N-th Tribonacci adds the last three numbers, so it keeps three.

Shifting k variables at every step gets clumsy. A small array of size k, used as a ring buffer, does it in one line. The answer for i goes into slot i % k. That slot holds the answer for i − k, the one about to fall out of the window, so we can write over it:

last = [0, 1, 1]                    // T0, T1, T2
for i from 3 to n:
    last[i % 3] = last[0] + last[1] + last[2]
return last[n % 3]

For n = 9, this gives 81, the same as the full table.

The same idea works on 2-D tables, one row at a time. When row i reads only row i − 1, two rows are enough. Often one row is enough, if it is updated in the right direction. The knapsack lesson shows why left to right and right to left give different answers.

8 Mistakes and edge cases

  • Shifting before computing. The loop below moves prev1 into prev2 first, so the formula adds the house to the total that already includes its neighbour. On [2, 3] it returns 5, robbing both houses. The answer is 3. On our street it returns 23, every house.
for i from 2 to n:
    prev2 = prev1
    prev1 = max(prev1, prev2 + nums[i - 1])  // prev2 is new
  • Starting one house too far. A start of prev1 = max(nums[0], nums[1]) reads nums[1], which does not exist on a street of one house. That is a Runtime Error. Starting from best[0] and best[1] covers every street.
  • Throwing away the table when the choices are asked for. If the problem wants the houses, not only the total, keep the table and walk back.
  • Using it when the formula reaches far back. In Word Break, the answer for i can read any earlier index, so no small window exists. The full table stays.

9 When to use it

Write the table version first and look at its formula. The sign is a fixed, small look-back: slot i reads only slot i − 1, slot i − 2, up to slot i − k, where k does not grow with n. Then k variables, or a ring buffer of size k, replace the table.

  • Two back. Climbing Stairs, Min Cost Climbing Stairs, House Robber and Decode Ways all fit in prev2 and prev1.
  • Three back. N-th Tribonacci keeps three values.
  • Not a fixed distance. Word Break and Perfect Squares read slots far behind, so they keep the table. In the next lesson, on increasing subsequences, each answer also looks at every earlier index.
Before keeping only a few variables, list the slots the formula reads. If that list has a fixed length and the problem wants only the final number, the rest of the table can go.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.