Minimum Number of Food Buckets to Feed the Hamsters - 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. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or at index i + 1.

Return the minimum number of food buckets you should place at empty indices to feed all the hamsters or -1 if it is impossible to feed all of them.

Input & Output

Example 1 — Basic Valid Case
$ Input: hamsters = "H..H.."
Output: 2
💡 Note: Place buckets at positions 1 and 4. H at position 0 is fed by bucket at 1, H at position 3 is fed by bucket at 4.
Example 2 — Impossible Case
$ Input: hamsters = ".HHH."
Output: -1
💡 Note: The middle hamster at position 2 cannot be fed because positions 1 and 3 are occupied by other hamsters.
Example 3 — Optimal Sharing
$ Input: hamsters = "H.H"
Output: 1
💡 Note: Place one bucket at position 1. It feeds both hamsters at positions 0 and 2.

Constraints

  • 1 ≤ hamsters.length ≤ 105
  • hamsters[i] is either 'H' or '.'

Visualization

Tap to expand
Minimum Food Buckets for Hamsters INPUT hamsters = "H..H.." H 0 . 1 . 2 H 3 . 4 H = Hamster . = Empty spot B = Food Bucket = Hungry hamster ALGORITHM STEPS 1 Scan Left to Right Find each hamster (H) 2 Check Right First Place bucket at i+1 if empty 3 Else Check Left Place bucket at i-1 if empty 4 Return -1 if stuck Both sides blocked: impossible Greedy Process: H B . Bucket feeds H[0] H B B Bucket feeds H[3] FINAL RESULT Final Configuration: H B . H B . Output: 2 OK - All Fed! 2 buckets, 2 hamsters Key Insight: Greedy: Always try to place bucket on RIGHT side first (index i+1). This allows the bucket to potentially feed a future hamster at i+2 as well, minimizing total buckets needed. Return -1 only when a hamster has 'H' on both sides (impossible to feed). TutorialsPoint - Minimum Number of Food Buckets to Feed the Hamsters | Greedy Approach Time: O(n) | Space: O(1)
Asked in
Amazon 15 Google 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
845 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