#2105

Watering Plants II

Medium
ArrayTwo PointersSimulationTwo PointersSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can optimize the simulation by determining the point where Alice and Bob would meet. Instead of checking each plant individually, we can calculate how much water they can use before they need to refill, allowing us to skip unnecessary iterations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize Alice's and Bob's water levels to their respective capacities and a refill counter to 0.
  2. 2Step 2: Use a while loop to simulate watering until both pointers meet.
  3. 3Step 3: Calculate how much water Alice can use before needing a refill and how much Bob can use.
  4. 4Step 4: If they meet, check who has more water to water the plant. If they have the same, Alice waters it.
  5. 5Step 5: Count refills as needed and return the total refills.
solution.py29 lines
1def wateringPlants(plants, capacityA, capacityB):
2    alice_water = capacityA
3    bob_water = capacityB
4    refills = 0
5    n = len(plants)
6    left = 0
7    right = n - 1
8
9    while left <= right:
10        if alice_water >= plants[left]:
11            alice_water -= plants[left]
12            left += 1
13        else:
14            refills += 1
15            alice_water = capacityA - plants[left]
16            left += 1
17
18        if left > right:
19            break
20
21        if bob_water >= plants[right]:
22            bob_water -= plants[right]
23            right -= 1
24        else:
25            refills += 1
26            bob_water = capacityB - plants[right]
27            right -= 1
28
29    return refills

Complexity note: The time complexity is O(n) because we only traverse the plants once, and the space complexity is O(1) as we are using a constant amount of space.

  • 1Alice and Bob can water plants simultaneously, which allows for a more efficient approach.
  • 2Understanding the refill mechanism is crucial to minimizing the number of refills.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.