Watering Plants II — LeetCode 2105 Python Solution

MediumArrayTwo PointersSimulation
Problem
#2105
Reading time
3 min

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.

Example

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.

Python solution

Python
class Solution:
    def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
        a, b = capacityA, capacityB
        ans = 0
        i, j = 0, len(plants) - 1
        while i < j:
            if a < plants[i]:
                ans += 1
                a = capacityA
            a -= plants[i]
            if b < plants[j]:
                ans += 1
                b = capacityB
            b -= plants[j]
            i, j = i + 1, j - 1
        ans += i == j and max(a, b) < plants[i]
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the plant array
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2105. Watering Plants II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2105. Watering Plants II?
LeetCode 2105. Watering Plants II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2105. Watering Plants II?
The Python solution on this page runs in O(n), where n is the length of the plant array.
What is the space complexity of LeetCode 2105. Watering Plants II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2105. Watering Plants II cover?
LeetCode 2105. Watering Plants II is tagged Array, Two Pointers and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview