Problem Description
Alice and Bob water n plants arranged in a row. Alice starts from the left and Bob from the right, watering one plant at a time concurrently. Each plant requires a certain amount of water and they refill their watering can when there isn’t enough water to completely water the plant. In case they meet at the same plant, the one with more water (or Alice if equal) waters it. The task is to compute how many times they need to refill their watering cans to water all plants.
Key Insights
- Two simultaneous pointers: one starting from the beginning (Alice) and one from the end (Bob).
- Each person checks if their remaining water is enough; if not, they refill before watering the plant.
- When both reach the same plant, compare remaining water to decide who will water it.
- Simulation of the watering process guarantees an O(n) time complexity as each plant is visited exactly once.
Space and Time Complexity
Time Complexity: O(n) since we traverse the plants array using two pointers. Space Complexity: O(1) as only a few extra variables are used.
Solution
We use a two-pointer approach, with one pointer for Alice (starting at index 0) and one for Bob (starting at index n-1). For each plant:
- Check if the current water is sufficient to water the plant.
- If not, refill (increase the counter) and deduct the water needed.
- When both pointers meet, determine who will water the plant by comparing the remaining water amounts; in case of a tie, Alice waters it. This simulation directly follows the problem rules and guarantees that we count each refill correctly.