KatInterview

797. Rabbits in Forest

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of rabbits in a forest, given an array answers where answers[i] is the number of other rabbits that have the same color as rabbit i. The core of the problem lies in interpreting these answers to form groups of rabbits by color.

Solution

Rabbits in Forest in Python

import collections
import math

class Solution:
    def numRabbits(self, answers: List[int]) -> int:
        # Use a Counter to count the frequency of each answer.
        counts = collections.Counter(answers)
        
        total_rabbits = 0
        # Iterate through the counter.
        for answer, count in counts.items():
            # If a rabbit answers y, it's in a group of y + 1 rabbits of the same color.
            group_size = answer + 1
            
            # We have 'count' rabbits that gave this answer.
            # Number of groups needed is ceil(count / group_size).
            num_groups = math.ceil(count / group_size)
            
            # The total number of rabbits for this color is num_groups * group_size.
            total_rabbits += int(num_groups * group_size)
            
        return total_rabbits

Rabbits in Forest in Java

class Solution {
    public int numRabbits(int[] answers) {
        // Use a HashMap to count the frequency of each answer.
        // Key: answer y, Value: number of rabbits that gave that answer.
        Map<Integer, Integer> counts = new HashMap<>();
        for (int ans : answers) {
            counts.put(ans, counts.getOrDefault(ans, 0) + 1);
        }

        int totalRabbits = 0;
        // Iterate through the map of counts.
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            int answer = entry.getKey();
            int count = entry.getValue();
            
            // If a rabbit answers y, it belongs to a group of y + 1 rabbits of the same color.
            int groupSize = answer + 1;
            
            // We have 'count' rabbits giving this answer.
            // Number of groups needed is ceil(count / groupSize).
            // Using integer arithmetic for ceiling division: (a + b - 1) / b
            int numGroups = (count + groupSize - 1) / groupSize;
            
            // Total rabbits for this color group(s) is numGroups * groupSize.
            totalRabbits += numGroups * groupSize;
        }

        return totalRabbits;
    }
}

Rabbits in Forest in C++

class Solution {
public:
    int numRabbits(vector<int>& answers) {
        // Use a hash map to count the frequency of each answer.
        // The key is the answer y, and the value is the number of rabbits that gave that answer.
        std::unordered_map<int, int> counts;
        for (int ans : answers) {
            counts[ans]++;
        }

        int totalRabbits = 0;
        // Iterate through the map of counts.
        for (auto const& [answer, count] : counts) {
            // If a rabbit answers y, it means it's in a group of y + 1 rabbits of the same color.
            int groupSize = answer + 1;
            
            // We have 'count' rabbits that gave this answer.
            // We need to find the minimum number of groups of size 'groupSize' to accommodate them.
            // Each group can contain up to 'groupSize' such rabbits.
            // The number of groups is ceil(count / groupSize).
            // Using integer arithmetic, ceil(a/b) is (a + b - 1) / b.
            int numGroups = (count + groupSize - 1) / groupSize;
            
            // The total number of rabbits for this color (or colors) is numGroups * groupSize.
            totalRabbits += numGroups * groupSize;
        }

        return totalRabbits;
    }
};

Rabbits in Forest in TypeScript

function numRabbits(answers: number[]): number {
    // Use a Map to count the frequency of each answer.
    const counts = new Map<number, number>();
    for (const ans of answers) {
        counts.set(ans, (counts.get(ans) || 0) + 1);
    }

    let totalRabbits = 0;
    // Iterate through the map of counts.
    for (const [answer, count] of counts.entries()) {
        // If a rabbit answers y, it's in a group of y + 1 rabbits of the same color.
        const groupSize = answer + 1;
        
        // We have 'count' rabbits that gave this answer.
        // Number of groups needed is ceil(count / groupSize).
        const numGroups = Math.ceil(count / groupSize);
        
        // The total number of rabbits for this color is numGroups * groupSize.
        totalRabbits += numGroups * groupSize;
    }

    return totalRabbits;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.