Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 20, 2025 22:24
Show Gist options
  • Save Ifihan/fd211035d25daf2366429743a81c3d0c to your computer and use it in GitHub Desktop.
Save Ifihan/fd211035d25daf2366429743a81c3d0c to your computer and use it in GitHub Desktop.
Rabbits in Forest

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment