Leetcode 781. Rabbits in Forest
The problem is to count the minimum number of rabbits that could be in the forest based on their answers. Each rabbit must answer “Y + 1” where ‘Y’ is the number of other rabbits that have the same color which it has.
Given an array of integers, where each integer answers[i]
represents the answer a rabbit gave, calculate the minimum number of rabbits that could be in the forest.
Example:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
- The two rabbits that answered "1" could both be of one color.
- The rabbit that answered "2" can't be the same color as the rabbits above. Hence, there would be at least 3 rabbits answering "2".
answers
array can be between 0 and 999. The length of the array can be between 1 and 1000.answers
array be empty?
answers[i]
gives the number of other rabbits with the same color. Therefore, if a rabbit says answers[i] = 2
, it means there are 2 other rabbits of the same color as it, totaling 3 rabbits with that color.answers[i] + 1
rabbits.n
rabbits say answers[i]
, the minimum number of groups of rabbits of that color will be (n // (answers[i] + 1)) + (n % (answers[i] + 1) != 0)
. The total number of rabbits for that answer will be the number of groups multiplied by answers[i] + 1
.Here’s the solution implemented in C++:
#include <vector>
#include <unordered_map>
#include <cmath>
using namespace std;
class Solution {
public:
int numRabbits(vector<int>& answers) {
unordered_map<int, int> count;
for (int answer : answers) {
count[answer]++;
}
int result = 0;
for (auto& [answer, num_rabbits] : count) {
int group_size = answer + 1;
int groups = ceil(static_cast<double>(num_rabbits) / group_size);
result += groups * group_size;
}
return result;
}
};
The time complexity of this solution is O(N), where N is the number of elements in the answers
array. This is because we go through the answers
list once to create the count map and then iterate through the counts of each unique answer.
The space complexity is also O(N) due to the unordered_map
used to store the count of each answer.
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?