Minimum Number of Food Buckets to Feed the Hamsters — LeetCode 2086 Python Solution

MediumGreedyStringDynamic Programming
Problem
#2086
Pattern
Greedy
Reading time
3 min

The problem

You are given a 0-indexed string hamsters where hamsters[i] is either: 'H' indicating that there is a hamster at index i, or '.' indicating that index i is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters.

Example

Input
hamsters = "H..H"
Output
2
Explanation
We place two food buckets at indices 1 and 2.

Python solution

Python
class Solution:
    def minimumBuckets(self, street: str) -> int:
        ans = 0
        i, n = 0, len(street)
        while i < n:
            if street[i] == 'H':
                if i + 1 < n and street[i + 1] == '.':
                    i += 2
                    ans += 1
                elif i and street[i - 1] == '.':
                    ans += 1
                else:
                    return -1
            i += 1
        return ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2086. Minimum Number of Food Buckets to Feed the Hamsters is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2086. Minimum Number of Food Buckets to Feed the Hamsters?
LeetCode 2086. Minimum Number of Food Buckets to Feed the Hamsters is rated Medium on LeetCode.
What topics does LeetCode 2086. Minimum Number of Food Buckets to Feed the Hamsters cover?
LeetCode 2086. Minimum Number of Food Buckets to Feed the Hamsters is tagged Greedy, String and Dynamic Programming 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