Watering Plants II solution and explanation
3 more videos on this problem
2015. Watering Plants II (Leetcode Medium)Programming Live with Larry · 7:18 · 282 views
Leetcode 2105: Watering Plants II | Greedy Approach | Java Solution Explained | HindiCoding Nation · 17:23 · 236 views
LeetCode 2105: Watering Plants IIAlitaCode · 28:31 · 6 views
Water Plant II Solution | DSA Placement Series |#microsoft #amazon #adobe #dsa #faang #codingSCALive · 10:53 · 1K views
The problem
Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:
- Alice waters the plants in order from left to right, starting from the
0thplant. Bob waters the plants in order from right to left, starting from the(n - 1)thplant. They begin watering the plants simultaneously. - It takes the same amount of time to water each plant regardless of how much water it needs.
- Alice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.
- In case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant.
Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.
Example 1:
Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5 Output: 1 Explanation: - Initially, Alice and Bob have 5 units of water each in their watering cans. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 3 units and 2 units of water respectively. - Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it. So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.
Example 2:
Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4 Output: 2 Explanation: - Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively. - Alice waters plant 0, Bob waters plant 3. - Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively. - Since neither of them have enough water for their current plants, they refill their cans and then water the plants. So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.
Example 3:
Input: plants = [5], capacityA = 10, capacityB = 8 Output: 0 Explanation: - There is only one plant. - Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant. So, the total number of times they have to refill is 0.
Constraints:
n == plants.length1 <= n <= 1051 <= plants[i] <= 106max(plants[i]) <= capacityA, capacityB <= 109
Approach overview
Problem Overview: An array plants represents the water required for each plant in a row. Alice starts watering from the left and Bob from the right, each with their own watering can capacity. When either person doesn’t have enough water for the next plant, they refill. The goal is to simulate the process and return the total number of refills needed.
Approach 1: Sequential Simulation with Special Handling (O(n) time, O(1) space)
Simulate the watering process step by step while tracking the remaining water for Alice and Bob. Alice moves left to right and Bob moves right to left. Before watering a plant, check if the remaining water is enough; if not, increment the refill counter and reset the water level to full capacity. The only special case occurs when both pointers reach the same plant. At that point, the person with more remaining water handles the plant; if neither has enough, one final refill is required. This approach mirrors the real-world process directly and keeps the logic easy to follow.
Approach 2: Two Pointer Technique (O(n) time, O(1) space)
Use two pointers: left starting at index 0 and right starting at n-1. Maintain two variables tracking Alice’s and Bob’s remaining water. On each step, process the plant at left for Alice and the plant at right for Bob, refilling whenever the remaining capacity is insufficient. After watering, move the pointers inward. When left == right, only one plant remains; whichever person has more water attempts it, and if both have insufficient water, count one extra refill. The key insight is that both workers operate independently until the pointers meet, making a two-pointer simulation a natural fit.
The algorithm scans the array once while maintaining constant state variables, so the complexity stays linear. No additional data structures are required beyond counters and remaining capacity variables.
Conceptually, the problem is a clean example of two pointers combined with straightforward simulation on an array. Many interview questions use the same pattern: process elements from both ends while maintaining independent state.
Recommended for interviews: The two pointer approach is what interviewers typically expect. It demonstrates that you can model two independent processes moving toward each other and handle the meeting point correctly. A straightforward simulation still works, but recognizing the two-pointer structure signals stronger algorithmic intuition.
Approach 1: Two Pointer Technique
In this approach, we utilize the two-pointer technique to handle the problem efficiently. Alice and Bob can be visualized as pointers starting at opposite ends of the array and moving towards each other. We keep track of their current water levels and refill when necessary as per the problem's conditions. We handle the case where both may try to water the same plant by checking their water levels and deciding accordingly.
def min_refills(plants, capacityA, capacityB):
refills = 0
a_index = 0
b_index = len(plants) - 1
a_water = capacityA
b_water = capacityB
while a_index <= b_index:
if a_index == b_index:
if a_water >= b_water:
if a_water < plants[a_index]:
a_water = capacityA
refills += 1
a_water -= plants[a_index]
else:
if b_water < plants[b_index]:
b_water = capacityB
refills += 1
b_water -= plants[b_index]
break
if a_water < plants[a_index]:
a_water = capacityA
refills += 1
a_water -= plants[a_index]
a_index += 1
if b_water < plants[b_index]:
b_water = capacityB
refills += 1
b_water -= plants[b_index]
b_index -= 1
return refills
plants = [2, 2, 3, 3]
capacityA = 5
capacityB = 5
print(min_refills(plants, capacityA, capacityB))public class WateringPlants {
public static int minRefills(int[] plants, int capacityA, int capacityB) {
int refills = 0;
int aIndex = 0;
int bIndex = plants.length - 1;
int aWater = capacityA;
int bWater = capacityB;
while (aIndex <= bIndex) {
if (aIndex == bIndex) {
if (aWater >= bWater) {
if (aWater < plants[aIndex]) { aWater = capacityA; refills++; }
aWater -= plants[aIndex];
} else {
if (bWater < plants[bIndex]) { bWater = capacityB; refills++; }
bWater -= plants[bIndex];
}
break;
}
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
aIndex++;
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
bIndex--;
}
return refills;
}
public static void main(String[] args) {
int[] plants = {2, 2, 3, 3};
int capacityA = 5;
int capacityB = 5;
System.out.println(minRefills(plants, capacityA, capacityB));
}
}#include <iostream>
#include <vector>
using namespace std;
int minRefills(vector<int>& plants, int capacityA, int capacityB) {
int refills = 0;
int aIndex = 0;
int bIndex = plants.size() - 1;
int aWater = capacityA;
int bWater = capacityB;
while (aIndex <= bIndex) {
if (aIndex == bIndex) {
if (aWater >= bWater) {
if (aWater < plants[aIndex]) aWater = capacityA, refills++;
aWater -= plants[aIndex];
} else {
if (bWater < plants[bIndex]) bWater = capacityB, refills++;
bWater -= plants[bIndex];
}
break;
}
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
aIndex++;
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
bIndex--;
}
return refills;
}
int main() {
vector<int> plants = {2, 2, 3, 3};
int capacityA = 5, capacityB = 5;
int refills = minRefills(plants, capacityA, capacityB);
cout << refills << endl;
return 0;
}function minRefills(plants, capacityA, capacityB) {
let refills = 0;
let aIndex = 0;
let bIndex = plants.length - 1;
let aWater = capacityA;
let bWater = capacityB;
while (aIndex <= bIndex) {
if (aIndex === bIndex) {
if (aWater >= bWater) {
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
} else {
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
}
break;
}
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
aIndex++;
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
bIndex--;
}
return refills;
}
let plants = [2, 2, 3, 3];
let capacityA = 5;
let capacityB = 5;
console.log(minRefills(plants, capacityA, capacityB));#include <stdio.h>
int minRefills(int* plants, int n, int capacityA, int capacityB) {
int refills = 0;
int aIndex = 0;
int bIndex = n - 1;
int aWater = capacityA;
int bWater = capacityB;
while (aIndex <= bIndex) {
if (aIndex == bIndex) {
if (aWater >= bWater) {
if (aWater < plants[aIndex]) aWater = capacityA, refills++;
aWater -= plants[aIndex];
} else {
if (bWater < plants[bIndex]) bWater = capacityB, refills++;
bWater -= plants[bIndex];
}
break;
}
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
aIndex++;
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
bIndex--;
}
return refills;
}
int main() {
int plants[] = {2, 2, 3, 3};
int n = sizeof(plants) / sizeof(plants[0]);
int capacityA = 5, capacityB = 5;
int refills = minRefills(plants, n, capacityA, capacityB);
printf("%d\n", refills);
return 0;
}using System;
class WateringPlants {
public static int MinRefills(int[] plants, int capacityA, int capacityB) {
int refills = 0;
int aIndex = 0;
int bIndex = plants.Length - 1;
int aWater = capacityA;
int bWater = capacityB;
while (aIndex <= bIndex) {
if (aIndex == bIndex) {
if (aWater >= bWater) {
if (aWater < plants[aIndex]) { aWater = capacityA; refills++; }
aWater -= plants[aIndex];
} else {
if (bWater < plants[bIndex]) { bWater = capacityB; refills++; }
bWater -= plants[bIndex];
}
break;
}
if (aWater < plants[aIndex]) {
aWater = capacityA;
refills++;
}
aWater -= plants[aIndex];
aIndex++;
if (bWater < plants[bIndex]) {
bWater = capacityB;
refills++;
}
bWater -= plants[bIndex];
bIndex--;
}
return refills;
}
static void Main() {
int[] plants = { 2, 2, 3, 3 };
int capacityA = 5, capacityB = 5;
int refills = MinRefills(plants, capacityA, capacityB);
Console.WriteLine(refills);
}
}The Python solution follows the two-pointer approach, managing the refilling logic as per the plant requirements and current water levels. It ensures correct processing when both Alice and Bob approach the same plant.
Time Complexity: O(n) since the plants array is traversed once.
Space Complexity: O(1) as no additional data structures are needed beyond the basic variables.
Approach 2: Sequential Simulation with Special Handling
In this method, we simulate the process step-by-step, with special handling when both pointers are on the same plant. We track the refill operations for each character individually and decide who waters the plant at their meeting point using their current water levels.
def special_min_refills(plants, capacityA, capacityB):
refillsA = 0
refillsB = 0
a_water = capacityA
b_water = capacityB
a, b = 0, len(plants) - 1
while a <= b:
if a == b:
if a_water >= b_water:
if a_water < plants[a]:
refillsA += 1
else:
if b_water < plants[b]:
refillsB += 1
break
if a_water < plants[a]:
refillsA += 1
a_water = capacityA
a_water -= plants[a]
if b_water < plants[b]:
refillsB += 1
b_water = capacityB
b_water -= plants[b]
a += 1
b -= 1
return refillsA + refillsB
plants = [2, 2, 3, 3]
capacityA = 5
capacityB = 5
print(special_min_refills(plants, capacityA, capacityB))public class WateringSpecial {
public static int specialMinRefills(int[] plants, int capacityA, int capacityB) {
int refillsA = 0, refillsB = 0;
int aWater = capacityA, bWater = capacityB;
for (int a = 0, b = plants.length - 1; a <= b; a++, b--) {
if (a == b) {
if (aWater >= bWater) {
if (aWater < plants[a]) refillsA++;
} else {
if (bWater < plants[b]) refillsB++;
}
break;
}
if (aWater < plants[a]) {
refillsA++;
aWater = capacityA;
}
aWater -= plants[a];
if (bWater < plants[b]) {
refillsB++;
bWater = capacityB;
}
bWater -= plants[b];
}
return refillsA + refillsB;
}
public static void main(String[] args) {
int[] plants = {2, 2, 3, 3};
int capacityA = 5;
int capacityB = 5;
System.out.println(specialMinRefills(plants, capacityA, capacityB));
}
}#include <iostream>
#include <vector>
using namespace std;
int specialMinRefills(vector<int>& plants, int capacityA, int capacityB) {
int refillsA = 0, refillsB = 0;
int aWater = capacityA, bWater = capacityB;
for (int a = 0, b = plants.size() - 1; a <= b; a++, b--) {
if (a == b) {
if (aWater >= bWater) {
if (aWater < plants[a]) refillsA++;
} else {
if (bWater < plants[b]) refillsB++;
}
break;
}
if (aWater < plants[a]) {
refillsA++;
aWater = capacityA;
}
aWater -= plants[a];
if (bWater < plants[b]) {
refillsB++;
bWater = capacityB;
}
bWater -= plants[b];
}
return refillsA + refillsB;
}
int main() {
vector<int> plants = {2, 2, 3, 3};
int capacityA = 5, capacityB = 5;
int refills = specialMinRefills(plants, capacityA, capacityB);
cout << refills << endl;
return 0;
}function specialMinRefills(plants, capacityA, capacityB) {
let refillsA = 0, refillsB = 0;
let aWater = capacityA, bWater = capacityB;
for (let a = 0, b = plants.length - 1; a <= b; a++, b--) {
if (a === b) {
if (aWater >= bWater) {
if (aWater < plants[a]) refillsA++;
} else {
if (bWater < plants[b]) refillsB++;
}
break;
}
if (aWater < plants[a]) {
refillsA++;
aWater = capacityA;
}
aWater -= plants[a];
if (bWater < plants[b]) {
refillsB++;
bWater = capacityB;
}
bWater -= plants[b];
}
return refillsA + refillsB;
}
let plants = [2, 2, 3, 3];
let capacityA = 5;
let capacityB = 5;
console.log(specialMinRefills(plants, capacityA, capacityB));#include <stdio.h>
int specialMinRefills(int* plants, int n, int capacityA, int capacityB) {
int refillsA = 0, refillsB = 0;
int aWater = capacityA, bWater = capacityB;
for (int a = 0, b = n - 1; a <= b; a++, b--) {
if (a == b) {
if (aWater >= bWater) {
if (aWater < plants[a]) refillsA++;
} else {
if (bWater < plants[b]) refillsB++;
}
break;
}
if (aWater < plants[a]) {
refillsA++;
aWater = capacityA;
}
aWater -= plants[a];
if (bWater < plants[b]) {
refillsB++;
bWater = capacityB;
}
bWater -= plants[b];
}
return refillsA + refillsB;
}
int main() {
int plants[] = {2, 2, 3, 3};
int n = sizeof(plants) / sizeof(plants[0]);
int capacityA = 5, capacityB = 5;
printf("%d\n", specialMinRefills(plants, n, capacityA, capacityB));
return 0;
}using System;
class SpecialWatering {
public static int SpecialMinRefills(int[] plants, int capacityA, int capacityB) {
int refillsA = 0, refillsB = 0;
int aWater = capacityA, bWater = capacityB;
for (int a = 0, b = plants.Length - 1; a <= b; a++, b--) {
if (a == b) {
if (aWater >= bWater) {
if (aWater < plants[a]) refillsA++;
} else {
if (bWater < plants[b]) refillsB++;
}
break;
}
if (aWater < plants[a]) {
refillsA++;
aWater = capacityA;
}
aWater -= plants[a];
if (bWater < plants[b]) {
refillsB++;
bWater = capacityB;
}
bWater -= plants[b];
}
return refillsA + refillsB;
}
static void Main() {
int[] plants = { 2, 2, 3, 3 };
int capacityA = 5, capacityB = 5;
Console.WriteLine(SpecialMinRefills(plants, capacityA, capacityB));
}
}The Python solution uses stepwise simulation from both ends, tackling plant watering and refills with special logic when both reach the same plant, allowing decision-making based on water levels.
Time Complexity: O(n) due to a single pass through the array.
Space Complexity: O(1) as it is using constant space.
Approach 3: Two Pointers + Simulation
We use two variables a and b to represent the amount of water Alice and Bob have, initially a = capacityA, b = capacityB. Then we use two pointers i and j to point to the head and tail of the plant array, and simulate the process of Alice and Bob watering from both ends to the middle.
When i < j, we judge whether Alice and Bob have enough water to water the plants. If not, we refill the watering cans. Then we update the amount of water a and b, and move the pointers i and j. Finally, we need to judge whether i and j are equal. If they are equal, we need to judge whether max(a, b) is less than the amount of water the plant needs. If it is less, we need to refill the watering cans again.
The time complexity is O(n), where n is the length of the plant array. The space complexity is O(1).
function minimumRefill(plants: number[], capacityA: number, capacityB: number): number {
let [a, b] = [capacityA, capacityB];
let ans = 0;
let [i, j] = [0, plants.length - 1];
for (; i < j; ++i, --j) {
if (a < plants[i]) {
++ans;
a = capacityA;
}
a -= plants[i];
if (b < plants[j]) {
++ans;
b = capacityB;
}
b -= plants[j];
}
ans += i === j && Math.max(a, b) < plants[i] ? 1 : 0;
return ans;
}func minimumRefill(plants []int, capacityA int, capacityB int) (ans int) {
a, b := capacityA, capacityB
i, j := 0, len(plants)-1
for ; i < j; i, j = i+1, j-1 {
if a < plants[i] {
ans++
a = capacityA
}
a -= plants[i]
if b < plants[j] {
ans++
b = capacityB
}
b -= plants[j]
}
if i == j && max(a, b) < plants[i] {
ans++
}
return
}impl Solution {
pub fn minimum_refill(plants: Vec<i32>, capacity_a: i32, capacity_b: i32) -> i32 {
let mut a = capacity_a;
let mut b = capacity_b;
let mut ans = 0;
let mut i = 0;
let mut j = plants.len() - 1;
while i < j {
if a < plants[i] {
ans += 1;
a = capacity_a;
}
a -= plants[i];
if b < plants[j] {
ans += 1;
b = capacity_b;
}
b -= plants[j];
i += 1;
j -= 1;
}
if i == j && a.max(b) < plants[i] {
ans += 1;
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two Pointer Technique | Time Complexity: O(n) since the plants array is traversed once. |
| Sequential Simulation with Special Handling | Time Complexity: O(n) due to a single pass through the array. |
| Two Pointers + Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sequential Simulation with Special Handling | O(n) | O(1) | When implementing the process exactly as described with explicit refill checks for Alice and Bob |
| Two Pointer Technique | O(n) | O(1) | Best general solution when processing elements from both ends of an array simultaneously |
Frequently asked questions
Is Watering Plants II easy or hard?
Watering Plants II is rated Medium on LeetCode. The core logic is simple, but handling the meeting point when both pointers reach the same plant and managing refill conditions correctly makes it slightly tricky.
Watering Plants II Python/Java solution
Both Python and Java implementations follow the same logic: maintain two pointers and track remaining water for Alice and Bob. Before watering a plant, check if the remaining capacity is enough; if not, increment the refill counter and reset the capacity. The algorithm runs in O(n) time and O(1) space in both languages.
How to solve Watering Plants II in O(n)?
Use two pointers representing Alice and Bob moving inward from opposite ends of the array. Track the remaining water in each watering can and increment a refill counter whenever the remaining capacity is insufficient. When both pointers meet at the same plant, check which person has more water or perform one extra refill if needed.
What is the best approach for Watering Plants II?
The optimal approach uses a two-pointer simulation. One pointer starts from the left for Alice and another from the right for Bob, tracking remaining water in both cans. Each step checks if a refill is needed before watering the next plant. This method processes the array once in O(n) time with O(1) extra space.
Is Watering Plants II asked at Google/Amazon/Meta?
Problems involving two-pointer simulation and resource tracking frequently appear in interviews at companies like Amazon, Google, and Meta. Watering Plants II itself or variations of it are used to test array traversal, edge-case handling, and simulation logic.
What data structure is used in Watering Plants II?
The problem primarily uses an array along with the two-pointer technique. No additional data structures such as stacks or hash maps are required. The solution relies on simple variables to track remaining water and the refill count.
What is the time complexity of Watering Plants II?
The time complexity is O(n) because each plant is processed exactly once as the two pointers move toward the center. The algorithm only maintains a few counters and capacity variables, so the space complexity remains O(1).
