Rabbits in Forest — LeetCode 781 Python Solution
- Problem
- #781
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.