#2086
Minimum Number of Food Buckets to Feed the Hamsters
MediumStringDynamic ProgrammingGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a greedy strategy to place food buckets efficiently. By scanning the string and placing buckets strategically, we minimize the number of buckets needed while ensuring all hamsters are fed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter for food buckets and iterate through the string.
- 2Step 2: When a hamster is found, check the adjacent indices for empty spaces.
- 3Step 3: Place a food bucket in the optimal position (preferably to the right) to cover the current and next hamster if possible.
- 4Step 4: Continue until all hamsters are processed or determine if feeding is impossible.
solution.py17 lines
1def minFoodBuckets(hamsters):
2 n = len(hamsters)
3 buckets = 0
4 i = 0
5 while i < n:
6 if hamsters[i] == 'H':
7 if i + 1 < n and hamsters[i + 1] == '.':
8 buckets += 1
9 i += 2 # Skip next index as it's covered
10 elif i - 1 >= 0 and hamsters[i - 1] == '.':
11 buckets += 1
12 i += 1 # Move to next hamster
13 else:
14 return -1
15 else:
16 i += 1
17 return bucketsℹ
Complexity note: The complexity is O(n) because we make a single pass through the string, checking and placing buckets as needed.
- 1Hamsters must have adjacent empty spaces to be fed; otherwise, it's impossible.
- 2Placing buckets optimally (preferably to the right) minimizes the total number needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.