The empty prefix
transcript
Reactions arrive as ups and downs. You want the longest balanced stretch. The code looks right. It fails on the list one, zero. The cause is the empty prefix.
Score an up as plus one and a down as minus one. The balances are one, then zero. Zero needs an earlier zero to pair with.
An empty map has no earlier zero. The answer is zero. Seed zero at index minus one. That is the empty prefix. Now the pair forms, and the answer is two.
Seed the map with balance zero at minus one. Keep the first index of every balance. The run length is the later index minus the earlier.
A prefix exists before the first item. It is empty. Its balance is zero, as its total is empty. A run from the start pairs with it.
Start the map with balance zero. Store the index minus one. Test a list that is balanced from the start. Full breakdown in the lecture.