Skip to content

Commit 7b73da5

Browse files
authored
Create rabbits-in-forest.py
1 parent ea535c9 commit 7b73da5

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Python/rabbits-in-forest.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# In a forest, each rabbit has some color.
5+
# Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them.
6+
# Those answers are placed in an array.
7+
#
8+
# Return the minimum number of rabbits that could be in the forest.
9+
#
10+
# Examples:
11+
# Input: answers = [1, 1, 2]
12+
# Output: 5
13+
# Explanation:
14+
# The two rabbits that answered "1" could both be the same color, say red.
15+
# The rabbit than answered "2" can't be red or the answers would be inconsistent.
16+
# Say the rabbit that answered "2" was blue.
17+
# Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
18+
# The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
19+
#
20+
# Input: answers = [10, 10, 10]
21+
# Output: 11
22+
#
23+
# Input: answers = []
24+
# Output: 0
25+
#
26+
# Note:
27+
# - answers will have length at most 1000.
28+
# - Each answers[i] will be an integer in the range [0, 999].
29+
30+
class Solution(object):
31+
def numRabbits(self, answers):
32+
"""
33+
:type answers: List[int]
34+
:rtype: int
35+
"""
36+
count = collections.Counter(answers)
37+
return sum((((k+1)+v-1)//(k+1))*(k+1) for k, v in count.iteritems())

0 commit comments

Comments
 (0)