LeetCode 781: Rabbits in Forest Solution

Master LeetCode problem 781 (Rabbits in Forest), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

781. Rabbits in Forest

Problem Explanation

Explanation:

To solve this problem, we need to find the minimum number of rabbits that could be in the forest given the answers provided by the rabbits. The key observation is that for a rabbit that answers "x", there can be at most x+1 rabbits with the same color. If there are more than x+1 rabbits with the same color, they would have different answers which contradict the information given.

Therefore, we can keep track of the count of rabbits of each color using a hashmap. For each rabbit's answer, we update the count of rabbits with that color. If the count exceeds the answer, we add (answer + 1) to the result which represents the current rabbit and additional rabbits of the same color. :

Solution Code

class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer, Integer> map = new HashMap<>();
        int result = 0;
        
        for (int answer : answers) {
            int count = map.getOrDefault(answer, 0);
            if (count % (answer + 1) == 0) {
                result += answer + 1;
            }
            map.put(answer, count + 1);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 781 (Rabbits in Forest)?

This page provides optimized solutions for LeetCode problem 781 (Rabbits in Forest) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 781 (Rabbits in Forest)?

The time complexity for LeetCode 781 (Rabbits in Forest) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 781 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 781 in Java, C++, or Python.

Back to LeetCode Solutions