All problems
1164MediumArrayHash TableMathGreedy

The Fewest Moths in the Jar

Tracked in this browser only
Write code

Trains the technique from

LeetCode 781Rabbits in Forest

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Some of the moths in a jar were asked how many other moths share their own pattern, and replies holds the answers given, one per moth asked. Moths that were not asked said nothing.

A moth answering x belongs to a group of exactly x + 1 moths sharing one pattern, and moths in different groups never share a pattern.

Return the fewest moths the jar could hold.

Examples

Example 1

Input
replies = [1, 1, 1]
Output
4

Two of the three moths can share a group of two, but the third needs a group of two of its own, so a fourth moth must be there unasked.

Example 2

Input
replies = [0, 1, 2, 3]
Output
10

Each answer names a different group size, so the four groups hold one, two, three and four moths.

Example 3

Input
replies = [2, 2, 2, 2]
Output
6

Groups of three are named. Three of the four moths fill one group and the fourth opens another, which needs two more moths to fill it.

Constraints

  • 1 <= replies.length <= 1000
  • 0 <= replies[i] < 1000

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def num_rabbits(replies: list[int]) -> int:
Java
public int numRabbits(int[] replies)
September 7
Apply