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
Understanding the Visualization
1
Input Analysis
String with H (hamsters) and . (empty spots)
2
Greedy Placement
Place buckets to feed maximum hamsters
3
Optimal Result
Minimum number of buckets needed
Key Takeaway
🎯 Key Insight: Place food buckets as far right as possible to potentially feed multiple hamsters with each bucket
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code