Minimum Number of Food Buckets to Feed the Hamsters - Problem

You're managing a hamster habitat represented by a string where each position can either contain a hamster ('H') or be empty ('.'). Your goal is to strategically place food buckets in empty positions to feed all the hamsters using the minimum number of buckets possible.

A hamster can be fed if there's at least one food bucket in an adjacent position (either immediately to its left or right). For example, if there's a hamster at position i, placing a food bucket at position i-1 or i+1 will satisfy that hamster's needs.

The Challenge: Find the minimum number of food buckets needed to feed all hamsters, or return -1 if it's impossible to feed them all.

Examples:
"H.H" → Need 1 bucket in the middle: "HFH"
"HHH" → Impossible! Adjacent hamsters can't share food buckets
"H..H" → Need 2 buckets: "HF.FH" or optimize to 1: "H.FH"

Input & Output

example_1.py — Basic Case
$ Input: hamsters = "H.H"
Output: 1
💡 Note: Place one food bucket at position 1. The bucket feeds both hamsters at positions 0 and 2.
example_2.py — Impossible Case
$ Input: hamsters = "HHH"
Output: -1
💡 Note: It's impossible to feed all hamsters because consecutive hamsters cannot share the same food bucket, and there are no empty positions.
example_3.py — Optimal Placement
$ Input: hamsters = "H..H"
Output: 1
💡 Note: We can place one food bucket at position 1 or 2. Either position feeds both hamsters, so the minimum is 1.

Constraints

  • 1 ≤ hamsters.length ≤ 105
  • hamsters[i] is either 'H' or '.'
  • Each hamster must be fed by at least one adjacent bucket
  • Food buckets can only be placed in empty positions ('.')

Visualization

Tap to expand
Night Street Lighting AnalogyHouses need illumination (hamsters need feeding)🏠🏠🏠🏠Step 1: Place light optimally to illuminate maximum houses🏠💡🏠🏠🏠Step 2: Place second light for remaining unlit houses🏠💡🏠🏠💡🏠✅ All houses illuminated with minimum lights!Greedy Strategy: Always place light to cover maximum future houses
Understanding the Visualization
1
Scan the Street
Walk from left to right, checking each house (hamster)
2
Smart Light Placement
When you find a dark house, place the light to illuminate maximum future houses
3
Avoid Redundancy
Skip houses that are already illuminated by previous lights
4
Handle Impossible Cases
Some configurations (like adjacent houses with no space) are impossible to light
Key Takeaway
🎯 Key Insight: The greedy approach works because placing a bucket to the right (when possible) never makes the solution worse, and often makes it better by potentially feeding future hamsters.
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
34.2K Views
Medium-High Frequency
~18 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen