Problem Description
You are given a 0-indexed string hamsters where hamsters[i] is either 'H' (indicating there is a hamster at index i) or '.' (indicating an empty index). You must place food buckets at some empty indices so that every hamster can be fed. A hamster is fed if there is at least one food bucket immediately to its left or right. Return the minimum number of buckets you need to place, or -1 if it is impossible to feed all hamsters.
Key Insights
- Use a greedy approach to place buckets in a way that can potentially feed more than one hamster.
- Prioritize placing a bucket at the right neighbor of a hamster if possible, since it may also cover a hamster further to the right.
- Always check if a hamster is already fed by a bucket placed to its left before trying to add a new bucket.
- If a hamster has neither neighbor available for bucket placement, the answer is -1.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) extra space if using the input string converted to a mutable array.
Solution
The main idea is to iterate over the string and for every hamster:
- If its left neighbor already has a bucket, continue.
- Otherwise, if its right neighbor is available (i.e., an empty cell '.'), place a bucket there.
- If the right neighbor is not available but the left neighbor is (and hasn’t been used already), place a bucket there.
- If neither neighbor can be used, return -1 since that hamster cannot be fed. We mark the placed buckets by modifying the array (or string) to denote positions where buckets have been placed. This ensures that subsequent hamsters can recognize if they are already fed by a neighboring bucket.