Skip to content
Related Articles

Related Articles

Improve Article

Minimum number of rabbits that must be present in the forest

  • Difficulty Level : Hard
  • Last Updated : 18 Aug, 2021

There are some colored rabbits in a forest. Given an array arr[] of size N, such that arr[i] denotes the number of rabbits having same color as the ith rabbit, the task is to find the minimum number of rabbits that could be in the forest.

Examples:

Input: arr[] = {2, 2, 0}
Output: 4
Explanation: Considering the 1st and the 2nd rabbits to be of same color, eg. Blue, there should be 3 blue-colored rabbits. The third rabbit is the only rabbit of that color. Therefore, the minimum number of rabbits that could be present in the forest are = 3 + 1 = 4.

Input: arr[] = {10, 10, 10}
Output: 11
Explanation: Considering all the rabbits to be of the same color, the minimum number of rabbits present in forest are 10 + 1 = 11.

Approach: The approach to solving this problem is to find the number of groups of rabbits that have the same color and the number of rabbits in each group. Below are the steps:



  • Initialize a variable count to store the number of rabbits in each group.
  • Initialize a map and traverse the array having key as arr[i] and value as occurrences of arr[i] in the given array.
  • Now, if y rabbits answered x, then:
    • If (y%(x + 1)) is 0, then there must be (y / (x + 1)) groups of (x + 1) rabbits.
    • If (y % (x + 1)) is non-zero, then there must be (y / (x + 1)) + 1 groups of (x + 1) rabbits.
  • Add the product of the number of groups and the number of rabbits in each group to the variable count.
  • After the above steps, the value of count gives the minimum number of rabbits in the forest.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// number of rabbits in the forest
int minNumberOfRabbits(int answers[], int N)
{
 
    // Initialize map
    map<int, int> Map;
 
    // Traverse array and map arr[i]
    // to the number of occurences
    for (int a = 0; a < N; a++) {
        Map[answers[a]]++;
    }
 
    // Initialize count as 0;
    int count = 0;
 
    // Find the number groups and
    // no. of rabbits in each group
    for (auto a : Map) {
        int x = a.first;
        int y = a.second;
 
        // Find number of groups and
        // multiply them with number
        // of rabbits in each group
        if (y % (x + 1) == 0)
            count = count + (y / (x + 1)) * (x + 1);
        else
            count = count + ((y / (x + 1)) + 1) * (x + 1);
    }
 
    // count gives minimum number
    // of rabbits in the forest
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 2, 0 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << minNumberOfRabbits(arr, N) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07

Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find the minimum
    // number of rabbits in the forest
    public static int minNumberOfRabbits(int[] answers,
                                         int N)
    {
        // Initialize map
        Map<Integer, Integer> map
            = new HashMap<Integer, Integer>();
 
        // Traverse array and map arr[i]
        // to the number of occurences
        for (int a : answers) {
            map.put(a, map.getOrDefault(a, 0) + 1);
        }
 
        // Initialize count as 0;
        int count = 0;
 
        // Find the number groups and
        // no. of rabbits in each group
        for (int a : map.keySet()) {
            int x = a;
            int y = map.get(a);
 
            // Find number of groups and
            // multiply them with number
            // of rabbits in each group
            if (y % (x + 1) == 0) {
                count = count + (y / (x + 1)) * (x + 1);
            }
            else
                count
                    = count + ((y / (x + 1)) + 1) * (x + 1);
        }
 
        // count gives minimum number
        // of rabbits in the forest
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 2, 2, 0 };
        int N = arr.length;
 
        // Function Call
        System.out.println(minNumberOfRabbits(arr, N));
    }
}

Python3




# Python3 program for the above approach
 
# Function to find the minimum
# number of rabbits in the forest
 
 
def minNumberOfRabbits(answers, N):
 
    # Initialize map
    Map = {}
 
    # Traverse array and map arr[i]
    # to the number of occurences
    for a in range(N):
 
        if answers[a] in Map:
            Map[answers[a]] += 1
        else:
            Map[answers[a]] = 1
 
    # Initialize count as 0;
    count = 0
 
    # Find the number groups and
    # no. of rabbits in each group
    for a in Map:
 
        x = a
        y = Map[a]
 
        # Find number of groups and
        # multiply them with number
        # of rabbits in each group
        if (y % (x + 1) == 0):
            count = count + (y // (x + 1)) * (x + 1)
        else:
            count = count + ((y // (x + 1)) + 1) * (x + 1)
 
    # count gives minimum number
    # of rabbits in the forest
    return count
 
 
# Driver code
arr = [2, 2, 0]
N = len(arr)
 
# Function Call
print(minNumberOfRabbits(arr, N))
 
# This code is contributed by divyesh072019

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
 
    // Function to find the minimum
    // number of rabbits in the forest
    public static int minNumberOfRabbits(int[] answers,
                                         int N)
    {
 
        // Initialize map
        Dictionary<int, int> map
            = new Dictionary<int, int>();
 
        // Traverse array and map arr[i]
        // to the number of occurences
        for (int a = 0; a < N; a++) {
            if (map.ContainsKey(answers[a]))
                map[answers[a]] += 1;
            else
                map.Add(answers[a], 1);
        }
 
        // Initialize count as 0;
        int count = 0;
 
        // Find the number groups and
        // no. of rabbits in each group
        for (int a = 0; a < map.Count; a++) {
            int x = map.Keys.ElementAt(a);
            int y = map[x];
 
            // Find number of groups and
            // multiply them with number
            // of rabbits in each group
            if (y % (x + 1) == 0) {
                count = count + (y / (x + 1)) * (x + 1);
            }
            else
                count
                    = count + ((y / (x + 1)) + 1) * (x + 1);
        }
 
        // count gives minimum number
        // of rabbits in the forest
        return count;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 2, 2, 0 };
        int N = arr.Length;
 
        // Function Call
        Console.WriteLine(minNumberOfRabbits(arr, N));
    }
}
 
// This code is contributed by AnkitRai01

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the minimum
// number of rabbits in the forest
function minNumberOfRabbits(answers, N)
{
 
    // Initialize map
    var map = new Map();
 
    // Traverse array and map arr[i]
    // to the number of occurences
    for (var a = 0; a < N; a++) {
        if(map.has(answers[a]))
            map.set(answers[a], map.get(answers[a])+1)
        else
            map.set(answers[a], 1)
    }
 
    // Initialize count as 0;
    var count = 0;
 
    // Find the number groups and
    // no. of rabbits in each group
    map.forEach((value, key) => {
         
        var x = key;
        var y = value;
 
        // Find number of groups and
        // multiply them with number
        // of rabbits in each group
        if (y % (x + 1) == 0)
            count = count + parseInt(y / (x + 1)) * (x + 1);
        else
            count = count + (parseInt(y / (x + 1)) + 1) * (x + 1);
    });
 
    // count gives minimum number
    // of rabbits in the forest
    return count;
}
 
// Driver code
var arr = [2, 2, 0];
var N = arr.length;
 
// Function Call
document.write( minNumberOfRabbits(arr, N));
 
</script>
Output
4

Time Complexity: O(N)
Auxiliary Space: O(N)

Another solution is to use HashMap of the counts and decrease the count every time the same answers[i] is met. If the same answers[i] occur again and the count is zero, reset the count with answers[i]+1 and add to the answer variable. Below are the steps:

  • Initialize a variable count with zero.
  • Use an unordered map mp.
  • Traverse the array and do the following:
    • if answers[i] is set to zero, set mp[answers[i]] = answers[i]+1 and count=count+answers[i]+1
    • finally subtract the count from map, mp[answers[i]]–;
  • return the cnt as answer.

C++




// C++ program for the above approach
#include <iostream>
#include <unordered_map>
 
using namespace std;
 
// Function to find the minimum
// number of rabbits in the forest
int minNumberOfRabbits(int answers[], int n)
{
    // Initialize cnt variable
    int count = 0;
    // Initialize map
    unordered_map<int, int> mp;
    for (int i = 0; i < n; ++i) {
 
        // Add to the count if not found or
        // has exhausted the count of all the
        // number of rabbits of same colour
        if (mp[answers[i]] == 0) {
            count += answers[i] + 1;
            mp[answers[i]] = answers[i] + 1;
        }
        mp[answers[i]]--;
    }
 
    // count gives minimum number
    // of rabbits in the forest
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 10, 0 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << minNumberOfRabbits(arr, N) << endl;
 
    return 0;
}
 
// This code is contributed by Bhavna Soni - bhavna23
 
 
Output
4

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :