Watering Plants II - 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 i-th 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 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. 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 i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: plants = [2,1,1,3], capacityA = 4, capacityB = 4
Output: 2
💡 Note: Alice waters plants 0,1 (uses 3 water, has 1 left). Bob waters plant 3 (needs refill: 1 < 3), then plant 2. Total refills: 1 (Bob) + 1 (Alice for next round if needed) = 2
Example 2 — No Refills Needed
$ Input: plants = [1,1,1,1], capacityA = 4, capacityB = 4
Output: 0
💡 Note: Alice waters plants 0,1 (uses 2 water). Bob waters plants 3,2 (uses 2 water). No refills needed.
Example 3 — Odd Length Collision
$ Input: plants = [5], capacityA = 3, capacityB = 4
Output: 1
💡 Note: Both reach plant 0. Bob has more water (4 > 3), but 4 < 5, so Bob refills once to water the plant.

Constraints

  • n == plants.length
  • 1 ≤ n ≤ 105
  • 1 ≤ plants[i] ≤ 106
  • plants[i] ≤ capacityA, capacityB ≤ 109

Visualization

Tap to expand
Watering Plants II Problem Overview2113AliceBobCapacity: 4Capacity: 4Both move toward center, refill when water insufficientResult: Count total refills = 2
Understanding the Visualization
1
Input
Array of plant water needs and two watering can capacities
2
Process
Alice moves left→right, Bob moves right→left, both refill when needed
3
Output
Total number of refills required
Key Takeaway
🎯 Key Insight: Use two pointers to simulate Alice and Bob's convergent movement efficiently
Asked in
Amazon 12 Google 8 Microsoft 6 Meta 4
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen