Skip to content

781. Rabbits in Forest

https://leetcode.com/problems/rabbits-in-forest/

js
/**
 * @param {number[]} answers
 * @return {number}
 */
var numRabbits = function(answers) {
  const map = answers.reduce((ret, answer) => {
    ret[answer] = (ret[answer] || 0) + 1
    return ret
  }, {})

  return Object.entries(map).reduce((ret, [answer, count]) => {
    answer = Number(answer)
    ret += Math.ceil(count / (answer + 1)) * (answer + 1)
    return ret
  }, 0)
}
py
import math


class Solution:

    def numRabbits(self, answers):
        """
        :type answers: List[int]
        :rtype: int
        """
        counts = {}
        for answer in answers:
            counts[answer] = counts.get(answer, 0) + 1

        total = 0
        for answer, count in counts.items():
            total += math.ceil(count / (answer + 1)) * (answer + 1)

        return total