Rabbits in Forest

medium hash-map math greedy

Problem

Each rabbit reports how many other rabbits share its color. Compute the minimum number of rabbits possible in the forest.

Inputanswers=[1,1,2]
Output5
Two rabbits answering 1 share a color (2 total); three rabbits with the answering-2 rabbit (3 total) gives 5.

from collections import Counter
def numRabbits(answers):
    cnt = Counter(answers)
    ans = 0
    for x, c in cnt.items():
        group = x + 1
        ans += ((c + group - 1) // group) * group
    return ans
function numRabbits(answers) {
  const cnt = new Map();
  for (const a of answers) cnt.set(a, (cnt.get(a) || 0) + 1);
  let ans = 0;
  for (const [x, c] of cnt) {
    const group = x + 1;
    ans += Math.ceil(c / group) * group;
  }
  return ans;
}
int numRabbits(int[] answers) {
    Map<Integer,Integer> cnt = new HashMap<>();
    for (int a : answers) cnt.merge(a, 1, Integer::sum);
    int ans = 0;
    for (var e : cnt.entrySet()) {
        int x = e.getKey(), c = e.getValue(), group = x + 1;
        ans += ((c + group - 1) / group) * group;
    }
    return ans;
}
int numRabbits(vector<int>& answers) {
    unordered_map<int,int> cnt;
    for (int a : answers) cnt[a]++;
    int ans = 0;
    for (auto& [x, c] : cnt) {
        int group = x + 1;
        ans += ((c + group - 1) / group) * group;
    }
    return ans;
}
Time: O(n) Space: O(n)