Problem 781

Abstract / Summary

Groups of rabbits are given by their answers about how many in their group each rabbit sees others see.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0781.py

class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        unique = defaultdict(int)
        for a in answers:
            unique[a] += 1

        result = 0
        for u in unique:
            have = unique[u]
            while have > 0:
                # some rabbits of the same color plus the one you were talking to
                result += u + 1
                have   -= u + 1
                # unfortunately, multiple colors may have the same group size
                # and of course some modulo math would be faster

        return result
17 lines | 587 bytes | submitted October 24, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Hash Table
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “Rabbits in Forest” problem. It receives a list of integer answers, where each answer a indicates that a rabbit reports there are a other rabbits of the same colour. The goal is to compute the minimum total number of rabbits that could exist consistent with all answers. The algorithm builds a frequency map of the answers, then iterates over each distinct answer to accumulate the required number of rabbits, handling grouping and leftovers in a compact loop.

Key Steps

Building the frequency map

The first phase creates a dictionary that records how many times each answer appears.

unique = defaultdict(int)
for a in answers:
    unique[a] += 1

Using defaultdict(int) eliminates the need for explicit existence checks, allowing the count to be incremented directly. This step aggregates identical answers, which is essential for the grouping logic that follows.

Initialising the result accumulator

Before processing the groups, a variable to hold the running total is set to zero.

result = 0

Processing each distinct answer

The core of the algorithm iterates over the keys of the frequency map. For each distinct answer u, it extracts the number of rabbits that gave that answer (have) and repeatedly consumes them in batches of size u + 1.

for u in unique:
    have = unique[u]
    while have > 0:
        result += u + 1
        have   -= u + 1

The comment inside the loop clarifies the reasoning: each batch represents a colour group consisting of u other rabbits plus the rabbit that answered, totalling u + 1. By subtracting u + 1 from have, the loop accounts for the rabbits already placed into a colour group.

Returning the final count

After all distinct answers have been processed, the accumulated total is returned.

return result

Edge Cases Handled

When the input list answers is empty, the frequency map remains empty, the outer loop does not execute, and the function correctly returns 0.

If an answer value is 0, the algorithm treats it as a group size of 1 (u + 1). The while loop will add 1 to the result for each occurrence, which matches the interpretation that each rabbit claiming “no other rabbit of my colour” must be alone.

When the count of a particular answer does not divide evenly by u + 1, the while loop still processes the remaining rabbits. For example, with u = 2 and have = 5, the first iteration consumes three rabbits (adding 3 to the result) and leaves have = 2. The next iteration adds another 3 to the result, even though only two rabbits remain; this reflects the necessity of allocating a full colour group to satisfy the answer constraints, thereby covering the leftover rabbits.

The algorithm also correctly handles multiple distinct answers that share the same group size. Since each answer is processed independently, groups of the same size but different colours are counted separately, ensuring the minimum total is still achieved.

Performance Optimizations Observed

The use of a hash-based frequency map (defaultdict) provides constant-time updates for each element in the input list, avoiding repeated scans of the data.

Grouping rabbits by their reported answer and then processing them in batches of u + 1 dramatically reduces the number of arithmetic operations compared with a naïve per-rabbit approach. Instead of iterating once per rabbit, the inner while loop advances by the full group size each iteration, which is especially beneficial when many rabbits share the same answer.

The algorithm relies on simple integer arithmetic and avoids any auxiliary data structures beyond the frequency map and a few scalar variables, keeping the runtime overhead low.

By iterating directly over the keys of the frequency map, the code sidesteps the need for sorting or additional passes, preserving the linear relationship between input size and processing effort.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big field full of colorful rabbits. Each rabbit is shy and only tells you how many other rabbits of the same color are standing nearby. Some rabbits might say three, which means there are four rabbits of that color in total because the one talking counts too.

The code starts by making a list to count how many rabbits say each number. It looks at every rabbit one by one and drops them into small buckets based on the number they shouted. If many rabbits shout the same number, they belong to the same group.

After sorting, the code looks at each bucket. If a group has a specific size, the code calculates how many rabbits must be in that color group and adds that number to the total count. If there are more rabbits in the bucket than fit in one group, it starts a brand new group of that same color size until every rabbit has been counted. This way, all the little bunnies are accounted for, even if they are playing in different groups across the field.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.41 | σ = 1.52

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
zfang399 C++
30 links | 16 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   October 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality