I started by counting how many times each answer appeared. Each answer x
means the rabbit believes there are x + 1
rabbits of the same color (including itself). Multiple rabbits can share the same group only if they don’t exceed x + 1
in total.
So, for each unique answer x
:
- I grouped the rabbits in groups of size
x + 1
. - The number of such groups is the ceiling of
count / (x + 1)
. - Each group adds
x + 1
rabbits to the total.
class Solution:
def numRabbits(self, answers: List[int]) -> int:
count = Counter(answers)
total = 0
for x, freq in count.items():
group_size = x + 1
groups = ceil(freq / group_size)
total += groups * group_size
return total
- Time: O(n)
- Space: O(n)
