Rabbits in Forest — LeetCode 781 Python Solution

MediumGreedyArrayHash TableMath
Problem
#781
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
answers = [1,1,2]
Output
5
Explanation
The two rabbits that answered "1" could both be the same color, say red.

Python solution

Python
class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        cnt = Counter(answers)
        ans = 0
        for x, v in cnt.items():
            group = x + 1
            ans += (v + group - 1) // group * group
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 781. Rabbits in Forest is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 781. Rabbits in Forest?
LeetCode 781. Rabbits in Forest is rated Medium on LeetCode.
What is the time complexity of LeetCode 781. Rabbits in Forest?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 781. Rabbits in Forest?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 781. Rabbits in Forest cover?
LeetCode 781. Rabbits in Forest is tagged Greedy, Array, Hash Table and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview