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 - Minimum Count INPUT answers array 1 i=0 1 i=1 2 i=2 Rabbit Answers: "1 other" "1 other" "2 others" Each rabbit reports how many other rabbits share its color answers = [1, 1, 2] ALGORITHM STEPS 1 Count Frequencies Group rabbits by answer value Answer | Count 1 | 2 2 | 1 2 Calculate Groups If answer=k, group has k+1 3 For answer=1: 2 rabbits say "1" --> 1 group Group size = 1+1 = 2 4 For answer=2: 1 rabbit says "2" --> 1 group Group size = 2+1 = 3 ceil(count/(k+1)) * (k+1) FINAL RESULT Group 1 (Color A): 2 rabbits Each says "1 other" - OK Group 2 (Color B): 3 rabbits One asked says "2 others" - OK Total = 2 + 3 = 5 rabbits (minimum possible) Output: 5 Key Insight: If a rabbit says "k", there are k+1 rabbits of that color (itself + k others). We group rabbits by their answer and calculate minimum groups needed. For each answer k with count c, we need ceil(c/(k+1)) complete groups, each containing (k+1) rabbits. Sum all groups for the minimum total. TutorialsPoint - Rabbits in Forest | Optimal Solution
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