Leetcode 781. Rabbits in Forest
In a forest, each rabbit has some color. Some rabbits tell you how many other rabbits have the same color as them. You are given an integer array answers
, where answers[i]
is the answer of the i-th
rabbit.
Return the minimum number of rabbits that could be in the forest.
answers[i] == 0
mean?
answers[i] == 0
, it means that the rabbit claims it is the only rabbit with that color.answers
array or the numbers within it?
answers
will have a length in the range [1, 1000], and each element will be an integer in the range [0, 1000].answers
array without additional context about the colors.y
, if there are x
rabbits that say there are y
other rabbits of the same color, this means there are at most y + 1
rabbits of that color.y + 1
such rabbits, those must overflow into another group of y + 1
rabbits.y + 1
(i.e., (count + y) // (y + 1) * (y + 1)
).import java.util.HashMap;
import java.util.Map;
public class RabbitsInForest {
public int numRabbits(int[] answers) {
Map<Integer, Integer> answerCount = new HashMap<>();
// Count the occurrences of each answer
for (int answer : answers) {
answerCount.put(answer, answerCount.getOrDefault(answer, 0) + 1);
}
int minRabbits = 0;
// Calculate the minimum number of rabbits for each answer group
for (Map.Entry<Integer, Integer> entry : answerCount.entrySet()) {
int y = entry.getKey();
int count = entry.getValue();
// Calculate group size which is y + 1
int groupSize = y + 1;
// Calculate the number of groups needed
int groups = (count + groupSize - 1) / groupSize;
// Add the total number of rabbits in these groups
minRabbits += groups * groupSize;
}
return minRabbits;
}
public static void main(String[] args) {
RabbitsInForest rif = new RabbitsInForest();
int[] answers = {1, 1, 2};
System.out.println(rif.numRabbits(answers)); // Output: 5
}
}
answers
.This efficient approach ensures that we capture the least number of rabbits as inferred from their answers while adhering to the logic provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?