Rabbits in Forest (LeetCode 781): Solution and Explanation

Medium
Array
Hash table
Math
Greedy

Each rabbit you asked tells you how many other rabbits share its colour. Find the smallest forest consistent with all the answers. Group rabbits by their answer and pack each group into as few colours as possible.

Intuition

If a rabbit says x, its colour has exactly x + 1 rabbits in total: itself and x others. So the answer is really a statement about the size of a colour group.

Two rabbits with different answers live in groups of different sizes, so they cannot share a colour. Rabbits with the same answer can share, which is how we save rabbits.

But a group of size x + 1 holds at most x + 1 rabbits. If c rabbits all say x, the fewest groups that fit them is ceil(c / (x + 1)).

Every group you open contributes all x + 1 of its members to the forest, even the ones you never asked. So answer x adds ceil(c / (x + 1)) * (x + 1) rabbits.

Approach: Count and pack

  1. Count how many rabbits gave each answer.
  2. For each answer x with count c, compute groups = (c + x) // (x + 1), which is ceil(c / (x + 1)).
  3. Add groups * (x + 1) to the total.
  4. Return the total.

Step-by-step example

answers = [1,1,2]
  1. Counts: answer 1 given twice, answer 2 given once.
  2. Answer 1: groups have 2 members, ceil(2 / 2) = 1 group, 2 rabbits. Total 2.
  3. Answer 2: groups have 3 members, ceil(1 / 3) = 1 group, 3 rabbits, two of them unseen. Total 5.
  4. The answer is 5.

Code: Python, Java, C++

1class Solution:
2    def numRabbits(self, answers: List[int]) -> int:
3        count = {}
4        for a in answers:
5            count[a] = count.get(a, 0) + 1
6        total = 0
7        for x, c in count.items():
8            groups = (c + x) // (x + 1)
9            total += groups * (x + 1)
10        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Count and pack O(n)
Greedy pass with a remaining-seats map O(n)
Sort and sweep O(n log n)
Time

O(n)

One pass to count answers and one pass over the distinct answers.

Space

O(n)

The count map holds at most one entry per distinct answer. A fixed array of size 1000 also works.

Other approaches

Greedy pass with a remaining-seats map (time O(n), space O(n))

Walk the answers. If an open group for answer x still has free seats, seat the rabbit there. Otherwise open a new group, add x + 1 to the total and record x free seats. It gives the same result in one pass.

Sort and sweep (time O(n log n), space O(1) extra)

Sort the answers so equal values are adjacent, then take runs of up to x + 1 equal values as one group each. Correct but pays O(n log n) for the sort.

Common mistakes

  • Adding only the number of rabbits asked. The unseen members of each colour group count too.
  • Putting all rabbits with the same answer in one group. If more than x + 1 rabbits say x, they need several groups.
  • Forgetting answer 0. Each such rabbit is alone in its colour and contributes exactly 1.
  • Using c // (x + 1) instead of the ceiling, which drops a partly filled group.

Frequently asked questions

Why can rabbits with different answers never share a colour?

All rabbits of one colour see the same group size, so they must all give the same answer. Different answers mean different colours.

Why is packing groups as full as possible optimal?

Every opened group adds exactly x + 1 rabbits no matter how many of them were asked, so the total for answer x is the group size times the number of groups, and ceil(c / (x + 1)) is the fewest groups that can hold c rabbits.

Can the total overflow a 32-bit integer?

No. At most 1000 rabbits are asked and each contributes a group of at most 1000, so the total is at most 1,000,000.