Skip to content
Problem 781 · LeetCode 781(opens in a new tab)

Rabbits in Forest

MediumGreedy algorithms

A forest holds an unknown number of rabbits, each with one colour. You ask some of them the same question: how many other rabbits share your colour? Their replies are in answers, one number per rabbit asked.

Every rabbit tells the truth. Return the smallest number of rabbits the forest could hold, counting the ones you never asked.

Example 1

Input:  answers = [2, 0, 2, 2, 2]
Output: 7
Why:    four rabbits said 2, but a colour that says 2 has exactly
        3 members, so they need two colours of 3; plus a lone one
2 more examples and the constraints

Example 2

Input:  answers = [3, 3]
Output: 4
Why:    both can share one colour of 4; two of them were not asked

Example 3

Input:  answers = [0, 0, 1]
Output: 4
Why:    two rabbits alone in their colours, and a pair of which
        only one answered

Constraints

  • 1 ≤ answers.length ≤ 1,000
  • 0 ≤ answers[i] < 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort and fill groupsO(n log n)
  2. Count answers, round upO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 answersVerdict
Sort and fill groupsO(n log n)
Fine; the sort dominates
Count answers, round upO(n)
Best; one count and a formula

n = number of answers.

Edge cases to test

  • Answer 0. Each such rabbit is alone in its colour, so each adds exactly 1.
  • More equal answers than fit. Five rabbits saying 1 need three colours of 2: total 6, not 2.
  • One rabbit with a big answer. A single reply of 999 still means 1,000 rabbits.
  • All answers different. Every answer opens its own colour; the total is the sum of answer + 1.

Common mistakes

  • Adding x + 1 once per distinct answer, which ignores that a colour can hold only x + 1 rabbits.
  • Adding only the rabbits that answered instead of the whole colour size x + 1.
  • Rounding down: c // (x + 1) loses the last, partly filled colour.

How to talk through it

  1. 1Clarify. Does the count exclude the rabbit itself? Are unasked rabbits counted? (Yes to both.)
  2. 2Model one answer. A reply of x means a colour group of exactly x + 1 rabbits.
  3. 3Group equal answers. Rabbits with the same answer can share a colour, up to x + 1 per colour.
  4. 4Count and round up. c rabbits saying x need ceil(c / (x + 1)) colours, each worth x + 1.
  5. 5Test out loud. Try [0], [1, 1, 1] which needs 4, and five 1s which need 6.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?