Opening the reading…
Opening the reading…
2 POINTERS › TWO POINTER ON ARRAYS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Alice's next plant is always the leftmost unwatered plant, while Bob's next plant is always the rightmost unwatered plant. That means the entire unfinished garden is described by two indices, i and j. Each gardener only needs their current water and the number of refills so far; no earlier plant can affect which plant they choose next.
As long as i is smaller than j, the gardeners water different plants, so their actions are independent and can be simulated one after the other. When i equals j, both have reached the same plant. You must not let both water it: compare their remaining water, give the plant to Alice on a tie, and count at most one refill for that final plant.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | Each loop iteration removes two different plants, except for one final iteration that handles the meeting plant. Thus every plant is inspected and subtracted from a can exactly once, with no plant revisited after its pointer moves past it. |
| Space | O(1) extra | The algorithm stores only two indices, two current-water values, and the refill counter. The input array is not extra storage, and no output collection is created; the bound stays constant even when one gardener reaches the other end much earlier. |
#include <vector>
using namespace std;
class Solution {
public:
int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {
int n = plants.size();
int i = 0;
int j = n - 1;
int curA = capacityA;
int curB = capacityB;
int refills = 0;
while (i <= j) {
if (i == j) {
if (curA >= curB) {
if (curA < plants[i]) {
refills++;
curA = capacityA;
}
curA -= plants[i];
} else {
if (curB < plants[i]) {
refills++;
curB = capacityB;
}
curB -= plants[i];
}
break;
}
if (curA < plants[i]) {
refills++;
curA = capacityA;
}
curA -= plants[i];
i++;
if (curB < plants[j]) {
refills++;
curB = capacityB;
}
curB -= plants[j];
j--;
}
return refills;
}
};The i == j branch is deliberately before the ordinary left-and-right work. In that branch, comparing curA and curB decides who is allowed to water, and the chosen gardener may need one refill. The break prevents the same plant from entering either side of the normal simulation, so the meeting rule is applied once and only once.