Leetcode 2086: Minimum Number of Food Buckets to Feed the Hamsters

grid47
grid47
Exploring patterns and algorithms
Apr 12, 2024 8 min read

You are given a string representing hamster positions. The string consists of ‘H’ for a hamster and ‘.’ for an empty space. You must place food buckets in empty positions such that all hamsters are fed. A hamster is fed if a food bucket is placed at one of its adjacent positions. Your task is to return the minimum number of food buckets required to feed all the hamsters. If it is impossible, return -1.
Problem
Approach
Steps
Complexity
Input: You are given a string 'hamsters' of length n (1 <= n <= 10^5). The string consists of 'H' for hamster positions and '.' for empty positions.
Example: ".H.H."
Constraints:
• 1 <= hamsters.length <= 10^5
• hamsters[i] is either 'H' or '.'
Output: Return the minimum number of food buckets needed to feed all hamsters, or -1 if it is impossible to feed all hamsters.
Example: 2
Constraints:
• Return -1 if it's impossible to feed all hamsters.
Goal: We aim to feed all hamsters with the minimum number of food buckets placed in empty spaces.
Steps:
• Iterate through the string and find empty spaces ('.') near a hamster ('H').
• For each hamster, place a food bucket in an adjacent empty space if possible.
• If a hamster cannot be fed (no empty space next to it), return -1.
Goal: The input string can have a length up to 100,000. Hamster positions can only be marked by 'H' and empty positions by '.'.
Steps:
• 1 <= hamsters.length <= 10^5
• hamsters[i] is either 'H' or '.'
Assumptions:
• There is at least one hamster in the string.
• All empty spaces are potential places for food buckets.
Input: ".H.H."
Explanation: By placing a food bucket at index 2, both hamsters at indices 1 and 3 will be fed.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus