Problem
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 ith
rabbit.
Given the array answers
, return the minimum number of rabbits that could be
in the forest.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= answers.length <= 1000
0 <= answers[i] < 1000
Solution
Each rabbit in the forest can reply with a number, answers[i]
, which represents how many rabbits (including itself) have the same colour as it. If several rabbits give the same answer, they might belong to the same group. To determine the minimum number of rabbits in the forest, we can group the responses intelligently based on how many rabbits belong to the same colour group.
Method 1 - Greedy
Here is the approach:
- Group Responses:
- The answer
k
from one rabbit means there can be at mostk+1
rabbits in that colour group (including the rabbit itself). - For example, if a rabbit says
2
, it means there can be2+1=3
rabbits in its colour group. - Count how many rabbits give each response using a frequency dictionary.
- The answer
- Calculate Minimum Rabbits:
- For each unique response
k
, determine the minimum number of rabbits by grouping. - If there are
count
rabbits with a responsek
, and each group can accommodate up tok+1
rabbits, use(count + k) // (k + 1)
groups to compute the total rabbits needed for that response.
- For each unique response
- Edge Cases:
- If there are no responses (empty array), return 0.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- Creating a frequency dictionary takes
O(n)
. - Iterating through the dictionary and calculating groups is
O(u)
, whereu
is the number of unique responses (usually small compared ton
). - Overall complexity:
O(n)
.
- Creating a frequency dictionary takes
- 🧺 Space complexity:
O(u)
for storing frequency data.