Rabbits In Forest Problem
Description
LeetCode Problem 781.
There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the i^th rabbit.
Given the array answers, return the minimum number of rabbits that could be in the forest.
Example 1:
Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Example 2:
Input: answers = [10,10,10]
Output: 11
Constraints:
- 1 <= answers.length <= 1000
- 0 <= answers[i] < 1000
Solution
Approach: Count and Round Up to Full Groups
A rabbit that answers x belongs to a color group of exactly x + 1 rabbits. Rabbits with different answers can never share a color, so each answer value can be handled on its own.
Suppose count rabbits answered x. To use as few rabbits as possible, put them into the same color group whenever we can, but one group holds at most x + 1 of them. So they need ceil(count / (x + 1)) groups, and every group has x + 1 rabbits in the forest, whether or not they all answered:
- Count how many rabbits gave each answer.
- For each answer
xwith countcount, addceil(count / (x + 1)) * (x + 1).
The case that is easy to get wrong is a count larger than the group size. In [1,1,1], two rabbits can share a red group of 2, but the third must start a second group, so the answer is 4, not 2. A rabbit that answers 0 is alone in its color and always adds exactly 1.
Integer ceiling division is (count + groupSize - 1) / groupSize, which avoids floating point.
Complexity: O(n) time and O(n) space, where n is the length of answers.
import collections
class Solution:
def numRabbits(self, answers: List[int]) -> int:
total = 0
for answer, count in collections.Counter(answers).items():
group_size = answer + 1 # a rabbit answering x has x others of its color
groups = (count + group_size - 1) // group_size # ceil(count / group_size)
total += groups * group_size
return total
Now write it from memory
Close the write-up and solve it yourself against the tests.