Magicsheet logo

Rabbits in Forest

Medium
87.4%
Updated 6/1/2025

Rabbits in Forest

What is this problem about?

The Rabbits in Forest problem asks: in a forest, each rabbit reports how many other rabbits have the same color. Given these answers, find the minimum number of rabbits in the forest. The key insight: if k rabbits answer "x", they may or may not all be the same color — but each group of (x+1) same-colored rabbits produces exactly the same answer x. This coding problem uses a hash map with grouping math. The array, math, hash table, and greedy interview pattern is the core.

Why is this asked in interviews?

Apple, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because the minimum-count reasoning requires careful mathematical thinking: rabbits with answer x must form groups of size (x+1). If you have k such rabbits, you need ceil(k/(x+1)) distinct groups, each contributing (x+1) rabbits.

Algorithmic pattern used

Frequency count + ceiling division. Count frequency of each answer. For answer x with frequency f: number of groups needed = ceil(f / (x+1)). Total rabbits = sum(groups * (x+1)) for each distinct answer.

Example explanation

answers=[1,1,2]. Frequencies: {1:2, 2:1}.

  • Answer 1: groups = ceil(2/2) = 1. Rabbits = 1×2 = 2.
  • Answer 2: groups = ceil(1/3) = 1. Rabbits = 1×3 = 3. Total = 2+3 = 5 minimum rabbits.

answers=[10,10,10]: all say 10. Group size = 11. 3 rabbits, one group of 11 suffices. Total = 11.

Common mistakes candidates make

  • Adding (answer + 1) for each rabbit instead of grouping.
  • Not using ceiling division (floor gives wrong minimum count).
  • Forgetting that rabbits with same answer CAN be different colors.
  • Off-by-one: group size is (x+1), not x.

Interview preparation tip

Rabbits in Forest requires converting a counting problem into a grouping math problem. The formula ceil(count / group_size) appears in many bin-packing and grouping problems. Practice similar problems: "minimum number of groups of size k," "minimum containers needed." The key mathematical step is recognizing that each rabbit reporting "x" belongs to a group of size x+1.

Similar Questions