Watering Plants II — LeetCode 2105 Python Solution
- Problem
- #2105
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the plant array |
| Space | O(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.