Keep a running balance that tells you when to restart, and make two passes when a choice depends on both neighbours.
You work on a maps app for hikers. A trail runs in a circle past six huts. At hut i a hiker can refill the water bottle with refill[i] units, and the walk from hut i to the next hut uses use[i] units.
The bottle has no size limit and starts empty. Your team lead says: "Which hut should a hiker start from to walk the whole circle without running dry?"
| Hut | Refill | Use on the way to the next hut |
|---|---|---|
| 0 | 4 | 3 |
| 1 | 1 | 5 |
| 2 | 6 | 2 |
| 3 | 2 | 4 |
| 4 | 3 | 1 |
| 5 | 5 | 3 |
At each hut the hiker refills first and then walks on. The bottle must never go below 0 on the way, and the hiker must return to the start. If several huts work, the smallest number is the answer.
The first attempt is correct. Try each hut as the start, walk the whole circle with a running bottle, and stop at the first moment it goes below 0. Six huts and six steps each is 36 steps, which is nothing.
On a real route with 100,000 huts, each start can take up to 100,000 steps. The whole search is 100,000 × 100,000 = 10 billion steps. We need a method that uses what a failed start tells us.
A bank statement lists deposits and withdrawals, and the last column is the running balance after each line. Suppose you want to know from which line an account could have been opened with nothing in it, so that the balance never goes below zero.
If the balance first goes below zero at line 7, then no opening at lines 1 to 6 could have worked either. A later opening skips deposits that were already in the account, so it has even less money at line 7. The next line to try is line 8.
The huts are the lines, and the bottle is the balance. The picture hides one thing: on a circle the list wraps round, so a start that survives to the end must also survive the wrap. We deal with that in section 3.
A bank statement: if the running balance first goes below zero at line seven, no earlier opening could have worked. The picture hides the wrap round a circle.
A running balance is one number that you update at each step. It carries the past, so you never have to look back. This lesson shows two uses. One balance tells you when to restart.
Another is carried from each side when a result depends on both neighbours.
Predict what happens
Q A hiker starts at hut 0 and the bottle goes below 0 at hut 1. Which huts are now ruled out as starts?
Answer: B
A start at hut 1 skips the water the hiker took at hut 0 and reaches the same trouble with less. The next candidate is hut 2.
Keep three numbers: bottle, the water since the candidate start, total, the net gain over all huts, and start, the candidate hut. At each hut, add the net gain, which is refill minus use. When the bottle goes below 0, set start to the next hut and empty the bottle.
| Hut | Net gain | Bottle after the hut | Total so far | Candidate start |
|---|---|---|---|---|
| 0 | 4 - 3 = 1 | 1 | 1 | 0 |
| 1 | 1 - 5 = -4 | -3, so restart with 0 | -3 | 2 |
| 2 | 6 - 2 = 4 | 4 | 1 | 2 |
| 3 | 2 - 4 = -2 | 2 | -1 | 2 |
| 4 | 3 - 1 = 2 | 4 | 1 | 2 |
| 5 | 5 - 3 = 2 | 6 | 3 | 2 |
The total gain is 3, which is not negative, so the circle can be walked, and the answer is the candidate, hut 2. Huts 0, 1, 3 and 5 fail. Hut 0 goes to -3 at hut 1, and hut 1 goes to -4 at once. Hut 3 goes to -2, and hut 5 goes to -1 at hut 1.
Hut 4 also works, but hut 2 is smaller.
Exercise · Break it: Find the gains where an empty bottle ruins the start. This version restarts as soon as the bottle is 0 or less. Find a list of net gains where it names a different hut than the right rule, or none at all.
def safe_start(gains):
bottle = 0
total = 0
start = 0
for hut, gain in enumerate(gains):
bottle += gain
total += gain
if bottle <= 0:
start = hut + 1
bottle = 0
return start if total >= 0 else -1Keep a bottle and a total over the huts, and when the bottle goes below zero, restart at the next hut with an empty bottle.
A string of P (pass) and F (fail) is balanced when it has as many of each. Count P as +1 and F as -1. For PPFFPF the balance runs 1, 2, 1, 0, 1, 0.
It is 0 after PPFF and after PF, so those are the cuts. The most balanced pieces is 2.
Now a different kind of task. Six accounts are in a row with ratings 2, 5, 4, 3, 1 and 4. Each gets at least 1 bonus unit, and an account with a higher rating than a neighbour gets more units than that neighbour.
A pass from the left gives each account one more than its left neighbour when its rating is higher. A pass from the right does the same for the right neighbour, and keeps the larger value.
| Account | Rating | After the left pass | After the right pass |
|---|---|---|---|
| 0 | 2 | 1 | 1 |
| 1 | 5 | 2 | 4 |
| 2 | 4 | 1 | 3 |
| 3 | 3 | 1 | 2 |
| 4 | 1 | 1 | 1 |
| 5 | 4 | 2 | 2 |
The left pass alone gives 1, 2, 1, 1, 1, 2, which totals 8. It breaks the rule: account 2 has a higher rating than account 3, yet gets the same units.
After the right pass the units are 1, 4, 3, 2, 1, 2. They total 13, the fewest that follow every rule.
Exercise · Predict the output: What does the right pass change?. Seven accounts have these ratings, and each needs more units than a lower-rated neighbour. The program runs a left pass, then a right pass, and prints the units and their total. What does it print?
ratings = [1, 2, 4, 5, 3, 1, 2]
n = len(ratings)
units = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
units[i] = units[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
units[i] = max(units[i], units[i + 1] + 1)
print(*units, sum(units))Two passes: the left pass gives a lower bound for each account, the right pass gives another, and the larger value follows both rules.
Predict what happens
Q A pass from the left gives an account one unit, but its rating is higher than the account on its right, which has two units. What must the right pass do?
Answer: B
The rating is higher than the right neighbour's, so the account needs more units than that neighbour. Two plus one is three, which is larger than the one from the left pass.
Last lesson's scans needed a sort first. The scans here do not: they read the input in the order it comes, in a single pass or two. The site has no picture of a running balance yet, so the visualizer replays last lesson's sorted scan as a contrast. Watch how much depends on the sort key there.
Step by step: A scan after sorting by end time. The animated player loads in your browser.
Step by step: The same scan with the start time as the key. The animated player loads in your browser.
Predict what happens
Q A running balance goes below 0 at step j. What do you do next?
Answer: B
A failure rules out every start up to step j, so the next candidate is step j + 1. You never go back, so the scan costs one step for each input item.
The visualizer shows last lesson's scan, the kind that needs a sort. Pick a list of requests and a rule, step through it, and notice that the key alone decides the result. A running balance has no key to choose: the input fixes the order, and the proof in section 3 does the work.
Try these three, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Write P(k) for the total gain from the candidate start up to hut k. Suppose the bottle first goes below 0 at hut j. Then P(k) is 0 or more for every k before j, and P(j) is below 0.
Take a start s' after the candidate, up to hut j. The water it has at hut j is P(j) - P(s' - 1). Since P(s' - 1) is 0 or more, this is at most P(j), which is below 0. So s' fails too, at hut j or earlier.
When a running total drops below zero, every earlier start is ruled out. When a choice depends on both neighbours, one pass per side gives two lower bounds, and the larger one is enough.
After the last restart at hut c, the bottle never goes below 0 from c to the end of the list. Before c, the list splits into stretches that each ended below 0. Inside a stretch, the running total from hut 0 stays at or above its value where the stretch began, and the stretch ends lower. So the running total from hut 0 is lowest right before c.
Walk the circle from c. Round the wrap, the bottle at a hut k before c is the water from c to the end plus the running total to k.
That is at least the water from c to the end plus the running total right before c. This sum is the total over the circle. The total is not negative, so the bottle stays at 0 or more.
If the total is negative, no start works, because the whole circle uses more water than it gives. That is why total decides between the candidate and -1.
A pattern of brackets may contain a star that can be an opening bracket, a closing bracket or nothing. After each character, the possible numbers of open brackets form a range with no holes. A star turns the range [low, high] into [low - 1, high + 1].
A count below 0 is not allowed, so low stops at 0. If high goes below 0, every reading has failed. At the end, a match needs low to be 0.
Take the six accounts again. In any valid plan, an account in a rising run needs at least the run length, because each step up needs one more unit. That is a lower bound from the left. The same holds from the right.
Take the larger of the two bounds for each account. Say account i has a higher rating than its right neighbour. The right pass gave i one more than the neighbour's right bound, and the neighbour's left bound is 1 because its rating fell. So i beats both of the neighbour's bounds.
The left side works the same way. So the larger value follows every rule, and no valid plan gives any account less.
A total over two sides needs the sum of the two parts. Take moves-to-bring-every-box. The moves for boxes on the left grow by the box count at each step right. The right side works the same way, so two passes add to the answer.
Predict what happens
Q For ratings 2, 5, 4, 3, 1, 4 the left pass gives 1, 2, 1, 1, 1, 2. What does the right pass do to account 2 (rating 4, next rating 3)?
Answer: B
The rating of account 2 is higher than that of account 3, so account 2 needs more units. Account 3 ends with 2, so account 2 needs 3, which is larger than the 1 from the left pass.
Here is the running balance with a restart as code. safe_start returns the smallest hut from which the circle can be walked, or -1. The step markers [1] to [4] match the steps above.
def safe_start(gains):
# [1] bottle is the water since the candidate start; total is the net gain over the whole circle.
bottle = 0
total = 0
start = 0
for hut, gain in enumerate(gains):
# [2] Each hut adds its net gain to both the bottle and the total.
bottle += gain
total += gain
# [3] A negative bottle rules out every start from the candidate up to this hut.
if bottle < 0:
# [4] Restart at the next hut with an empty bottle.
start = hut + 1
bottle = 0
return start if total >= 0 else -1public int safeStart(int[] gains) {
// [1] bottle is the water since the candidate start; total is the net gain over the whole circle.
long bottle = 0;
long total = 0;
int start = 0;
for (int hut = 0; hut < gains.length; hut++) {
// [2] Each hut adds its net gain to both the bottle and the total.
bottle += gains[hut];
total += gains[hut];
// [3] A negative bottle rules out every start from the candidate up to this hut.
if (bottle < 0) {
// [4] Restart at the next hut with an empty bottle.
start = hut + 1;
bottle = 0;
}
}
return total >= 0 ? start : -1;
}int safeStart(vector<int> gains) {
// [1] bottle is the water since the candidate start; total is the net gain over the whole circle.
long long bottle = 0;
long long total = 0;
int start = 0;
for (int hut = 0; hut < (int)gains.size(); hut++) {
// [2] Each hut adds its net gain to both the bottle and the total.
bottle += gains[hut];
total += gains[hut];
// [3] A negative bottle rules out every start from the candidate up to this hut.
if (bottle < 0) {
// [4] Restart at the next hut with an empty bottle.
start = hut + 1;
bottle = 0;
}
}
return total >= 0 ? start : -1;
}function safeStart(gains) {
// [1] bottle is the water since the candidate start; total is the net gain over the whole circle.
let bottle = 0;
let total = 0;
let start = 0;
for (let hut = 0; hut < gains.length; hut++) {
// [2] Each hut adds its net gain to both the bottle and the total.
bottle += gains[hut];
total += gains[hut];
// [3] A negative bottle rules out every start from the candidate up to this hut.
if (bottle < 0) {
// [4] Restart at the next hut with an empty bottle.
start = hut + 1;
bottle = 0;
}
}
return total >= 0 ? start : -1;
}On the six huts this returns 2. The second kind of scan is two passes.
Exercise · Put it in order: Restart on a negative bottle. Arrange the lines into a function that returns the smallest hut from which the circle can be walked, or -1. The input is the net gain at each hut.
def safe_start(gains):
bottle = 0
total = 0
start = 0
for hut, gain in enumerate(gains):
bottle += gain
total += gain
if bottle < 0:
start = hut + 1
bottle = 0
return start if total >= 0 else -1
start = hut
return start if bottle >= 0 else -1Here is the distance from each slot of a row to the nearest box. It needs a pass from each side, and it keeps the smaller of the two distances.
def nearest_distance(slots):
n = len(slots)
# [1] A distance that no real slot reaches stands for "no box seen yet".
far = n + 1
answer = [far] * n
# [2] Left to right: the distance to the last box on the left grows by one each step and resets at a box.
since = far
for i in range(n):
since = 0 if slots[i] == '1' else since + 1
answer[i] = min(far, since)
# [3] Right to left: the same from the other side, keeping the smaller of the two distances.
since = far
for i in range(n - 1, -1, -1):
since = 0 if slots[i] == '1' else since + 1
answer[i] = min(answer[i], since)
# [4] With no box at all, no distance is real.
return answer if '1' in slots else [-1] * npublic int[] nearestDistance(String slots) {
int n = slots.length();
// [1] A distance that no real slot reaches stands for "no box seen yet".
int far = n + 1;
int[] answer = new int[n];
java.util.Arrays.fill(answer, far);
// [2] Left to right: the distance to the last box on the left grows by one each step and resets at a box.
int since = far;
for (int i = 0; i < n; i++) {
since = slots.charAt(i) == '1' ? 0 : since + 1;
answer[i] = Math.min(far, since);
}
// [3] Right to left: the same from the other side, keeping the smaller of the two distances.
since = far;
for (int i = n - 1; i >= 0; i--) {
since = slots.charAt(i) == '1' ? 0 : since + 1;
answer[i] = Math.min(answer[i], since);
}
// [4] With no box at all, no distance is real.
if (slots.indexOf('1') < 0) {
java.util.Arrays.fill(answer, -1);
}
return answer;
}vector<int> nearestDistance(string slots) {
int n = (int)slots.size();
// [1] A distance that no real slot reaches stands for "no box seen yet".
int far = n + 1;
vector<int> answer(n, far);
// [2] Left to right: the distance to the last box on the left grows by one each step and resets at a box.
int since = far;
for (int i = 0; i < n; i++) {
since = slots[i] == '1' ? 0 : since + 1;
answer[i] = min(far, since);
}
// [3] Right to left: the same from the other side, keeping the smaller of the two distances.
since = far;
for (int i = n - 1; i >= 0; i--) {
since = slots[i] == '1' ? 0 : since + 1;
answer[i] = min(answer[i], since);
}
// [4] With no box at all, no distance is real.
if (slots.find('1') == string::npos) {
fill(answer.begin(), answer.end(), -1);
}
return answer;
}function nearestDistance(slots) {
const n = slots.length;
// [1] A distance that no real slot reaches stands for "no box seen yet".
const far = n + 1;
const answer = new Array(n).fill(far);
// [2] Left to right: the distance to the last box on the left grows by one each step and resets at a box.
let since = far;
for (let i = 0; i < n; i++) {
since = slots[i] === '1' ? 0 : since + 1;
answer[i] = Math.min(far, since);
}
// [3] Right to left: the same from the other side, keeping the smaller of the two distances.
since = far;
for (let i = n - 1; i >= 0; i--) {
since = slots[i] === '1' ? 0 : since + 1;
answer[i] = Math.min(answer[i], since);
}
// [4] With no box at all, no distance is real.
return slots.includes('1') ? answer : new Array(n).fill(-1);
}For 0010001 the left pass gives 8, 8, 0, 1, 2, 3, 0, where 8 stands for "no box yet". The right pass brings slots 0, 1 and 5 down to 2, 1 and 1. The final answer is 2, 1, 0, 1, 2, 1, 0.
Exercise · Find the bug: The right pass that throws the left pass away. This code finds the distance from each slot to the nearest box, using a pass from each side. It gives huge distances for slots that have a box on the left. Which line is wrong?
def nearest_distance(slots):
n = len(slots)
far = n + 1
answer = [far] * n
since = far
for i in range(n):
since = 0 if slots[i] == '1' else since + 1
answer[i] = min(far, since)
since = far
for i in range(n - 1, -1, -1):
since = 0 if slots[i] == '1' else since + 1
answer[i] = since
return answer if '1' in slots else [-1] * nNow write it yourself. The lab has two functions, one for each scan.
safe_start(gains) returns the smallest hut from which the circle can be walked, or -1, given the net gain at each hut. For the gains 1, -4, 4, -2, 2, 2 the answer is 2.nearest_distance(slots) returns the distance from each slot to the nearest slot with a box, or -1 for every slot when there is no box. For 0010001 the answer is 2, 1, 0, 1, 2, 1, 0.Three rules keep it correct:
far before the second pass, so it does not invent a box past the end.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Try every start or every position | Running balance or two passes |
|---|---|---|
| Time to answer | O(n²): n starts with n steps each | O(n): one pass, or two |
| Steps for 100,000 items | about 10 billion | about 100,000, or 200,000 for two passes |
| Memory | O(1) to O(n) | O(1), or O(n) for the answers of a two-pass scan |
| Why it is right | Every start is tried | A failure removes starts, or each side gives a lower bound |
For 100,000 items, a scan costs 100,000 steps, and two passes cost 200,000. No sort is needed, so the cost is linear.
Use a running balance when a total must not go below a limit. Examples are a battery, a bank balance or a count of open brackets. A failure must also tell you which starts are gone.
Use two passes when the answer at each position depends on both sides. Each side's part must be carried by one number, such as a count, a distance or a total.
Words such as "never go below", "from which start", "the most pieces" and "for every position" are hints. State what the balance means in one sentence before you write the code.
Do not use the restart rule when the bottle has a size limit. Water above the limit is lost, so the running total is no longer the water in the bottle. Take a limit of 3 and gains [-4, 4].
The restart rule answers 1. But the bottle holds at most 3 after hut 1, so the walk ends at -1 and no start works.
Do not use two passes when a rule links accounts that are not neighbours, such as account i and account i + 2. Each pass carries only what the next neighbour needs, so it can miss such a rule. If the input is tiny, the first attempt that tries everything is fine, and it has no proof to get wrong.
return 0 if sum(gains) >= 0 else -1 looks natural, but on the gains [-1, 1] the total is 0 and the rule answers 0. A start at hut 0 goes to -1 at once. The answer is 1.
Checking only the total can name a start that fails. For gains minus one and one, the total is zero, but hut zero fails.
Writing start = hut + 1 without bottle = 0 carries the negative value into the next candidate. On the gains [-1, 0, 3] the bottle is -1 at hut 0 and stays -1 at hut 1. So the rule moves the candidate to hut 2 and answers 2.
A start at hut 1 already works, with 0, then 3, then 2, so the answer is 1.
In nearest_distance, the right pass must start with since = far, which means that no box has been seen yet. On 0100, a right pass that starts with since = 0 pretends that a box sits right past the end, so the last slot gets distance 1. The nearest box is 2 away. Start the right pass with since = far.
For ratings [2, 1] the left pass gives 1 and 1, which breaks the rule between the two accounts. The answer is 2 and 1, so the total is 3. Any scan that depends on both neighbours needs a second pass.
For the pattern *(, a star lowers low to -1, and the bracket raises it to 0, so a rule that never raises low to 0 answers true. But the star can only be empty or an opening bracket, and then the final bracket stays open, so the answer is false.
Explain the restart rule and the two passes in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Running balance
Q What is a running balance in a greedy scan?
Answer: B
A running balance is a single number that you update at each step. It carries the past, so you never have to look back.
Checkpoint · Where to restart
Q The gains at four huts of a circle are 2, -3, 4 and -1. Which hut is the smallest start that works?
Answer: C
The bottle is 2, then -1 at hut 1, so the candidate moves to hut 2. From hut 2 it runs 4, 3, 5 and 2 round the circle, and never goes below 0.
Checkpoint · Why skip
Q The bottle goes below 0 at hut j. Why are the starts between the candidate and hut j ruled out?
Answer: B
Every step before j had a running total of 0 or more. Starting later removes that part, so the water at hut j is no larger than the negative value the first start had.
Checkpoint · The total
Q The gains at three huts of a circle are -3, 1 and 1. What is the answer?
Answer: D
The total gain is -1, which is below zero. The circle uses more water than it gives, so no start works.
Checkpoint · Cut at zero
Q In the string PFFPPF, P counts +1 and F counts -1. What is the most balanced pieces it can be cut into?
Answer: C
The balance runs 1, 0, -1, 0, 1, 0. It is 0 three times, so the pieces are PF, FP and PF.
Checkpoint · A wildcard
Q The pattern is an opening bracket followed by a star. A star can be an opening bracket, a closing bracket or nothing. Can the brackets match?
Answer: A
The low bound is 1 after the bracket and 0 after the star, so 0 is reachable. Reading the star as a closing bracket gives a matching pair.
Checkpoint · Two passes
Q The ratings of four accounts are 1, 3, 2, 1. Each gets at least one unit, and a higher rating than a neighbour gets more units. What is the fewest total?
Answer: C
The left pass gives 1, 2, 1, 1. The right pass raises account 2 to 2 and account 1 to 3, so the units are 1, 3, 2, 1 and the total is 7.
Checkpoint · Combining
Q In a pass from each side to find the distance to the nearest box, how do you combine the two results at a slot?
Answer: C
The nearest box is the closer of the nearest on the left and the nearest on the right, so the smaller distance wins. A rule that must hold on both sides takes the larger value, and a total adds.
Checkpoint · A limit
Q When does the restart rule stop being safe?
Answer: B
With a limit, water above the limit is lost, and the argument that a later start has no more water than an earlier one fails. Then another method is needed.
Checkpoint · A restart bug
Q The gains are -1, 0 and 3. A rule restarts at the next hut but keeps the negative bottle. What does it answer, and what is right?
Answer: A
The kept bottle of -1 is still negative at hut 1, so the rule moves on to hut 2. Starting at hut 1 gives 0, 3 and 2, which works, so the answer is 1.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.