Rabbits in Forest - Problem

There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.

Given the array answers, return the minimum number of rabbits that could be in the forest.

Input & Output

Example 1 — Basic Grouping
$ Input: answers = [1,1,2]
Output: 5
💡 Note: Two rabbits answered 1, so they can form one group of 2 rabbits with same color. One rabbit answered 2, so it needs a group of 3 rabbits. Total: 2 + 3 = 5 rabbits minimum.
Example 2 — Multiple Groups
$ Input: answers = [10,10,10]
Output: 11
💡 Note: Three rabbits answered 10, meaning each claims there are 11 rabbits of its color (including itself). Since we have 3 such answers, they can all belong to the same group of 11 rabbits.
Example 3 — Single Rabbit
$ Input: answers = [1]
Output: 2
💡 Note: One rabbit answered 1, meaning there should be 2 rabbits of its color total (including itself).

Constraints

  • 1 ≤ answers.length ≤ 1000
  • 0 ≤ answers[i] ≤ 1000

Visualization

Tap to expand
Rabbits in Forest: Find Minimum CountINPUTPROCESSOUTPUTanswers[1,1,2]Rabbit responsesCount frequencies:answer 1: freq 2 → 1 group of 2answer 2: freq 1 → 1 group of 3Total: 2 + 3 = 5Minimum5rabbits total🐰 Each rabbit reports count of others with same colorGroup efficiently: same answers can belong to same color groupKey: Use ceiling division to minimize groups needed
Understanding the Visualization
1
Input
Array of rabbit answers about same-color count
2
Process
Group same answers and calculate minimum rabbits
3
Output
Minimum total rabbits in forest
Key Takeaway
🎯 Key Insight: Rabbits giving the same answer can be optimally grouped using frequency counting and ceiling division
Asked in
Google 25 Amazon 18 Facebook 15
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen