Watering Plants — LeetCode 2079 Python Solution

MediumArraySimulation
Problem
#2079
Reading time
3 min

The problem

You want to water n plants in your garden with a watering can. 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], capacity = 5
Output
14
Explanation
Start at the river with a full watering can:

Python solution

Python
class Solution:
    def wateringPlants(self, plants: List[int], capacity: int) -> int:
        ans, water = 0, capacity
        for i, p in enumerate(plants):
            if water >= p:
                water -= p
                ans += 1
            else:
                water = capacity - p
                ans += i * 2 + 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the number of plants
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2079. Watering Plants?
LeetCode 2079. Watering Plants is rated Medium on LeetCode.
What is the time complexity of LeetCode 2079. Watering Plants?
The Python solution on this page runs in O(n), where n is the number of plants.
What is the space complexity of LeetCode 2079. Watering Plants?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2079. Watering Plants cover?
LeetCode 2079. Watering Plants is tagged Array 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