Open In App

Minimum number of rabbits that must be present in the forest

Improve
Improve
Like Article
Like
Save
Share
Report

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 occurrences
    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 occurrences
        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 occurrences
    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 occurrences
        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 occurrences
    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


Java




// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to find the minimum
    // number of rabbits in the forest
    static int minNumberOfRabbits(int[] answers, int n)
    {
        // Initialize cnt variable
        int count = 0;
         
        // Initialize map
        HashMap<Integer, Integer> mp = new HashMap<Integer,Integer>();
     
        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.containsKey(answers[i]))
            {   
                 count += answers[i] + 1;
                 mp.put(answers[i],answers[i]+1);
             }
             if(mp.containsKey(answers[i]))
             mp.put(answers[i],mp.get(answers[i])-1);
        }
  
    // count gives minimum number
    // of rabbits in the forest
    return count;
}
     
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 10, 10, 0 };
        int N = arr.length;
 
        // Function Call
        System.out.println(minNumberOfRabbits(arr, N));
    }
}
 
// This code is contributed by Pushpesh Raj


Python3




# Python 3 program for the above approach
 
# Function to find the minimum
# number of rabbits in the forest
def minNumberOfRabbits(answers, n):
 
    # Initialize cnt variable
    count = 0
     
    # Initialize map
    mp = {}
    for i in range(n):
 
        # Add to the count if not found or
        # has exhausted the count of all the
        # number of rabbits of same colour
        if (answers[i] not in mp):
            count += answers[i] + 1
            mp[answers[i]] = answers[i] + 1
 
        mp[answers[i]] -= 1
 
    # count gives minimum number
    # of rabbits in the forest
    return count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [10, 10, 0]
    N = len(arr)
 
    # Function Call
    print(minNumberOfRabbits(arr, N))
 
    # This code is contributed by ukasp.


C#




// Include namespace system
using System;
using System.Collections.Generic;
 
using System.Collections;
 
public class GFG
{
    // Function to find the minimum
    // number of rabbits in the forest
    public static int minNumberOfRabbits(int[] answers, int n)
    {
        // Initialize cnt variable
        var count = 0;
       
        // Initialize map
        var mp = new Dictionary<int, int>();
        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.ContainsKey(answers[i]))
            {
                count += answers[i] + 1;
                mp[answers[i]] = answers[i] + 1;
            }
            if (mp.ContainsKey(answers[i]))
            {
                mp[answers[i]] = mp[answers[i]] - 1;
            }
        }
       
        // count gives minimum number
        // of rabbits in the forest
        return count;
    }
   
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = {10, 10, 0};
        var N = arr.Length;
       
        // Function Call
        Console.WriteLine(GFG.minNumberOfRabbits(arr, N));
    }
}
 
// This code is contributed by sourabhdalal0001.


Javascript




<script>
class GFG
{
    // Function to find the minimum
    // number of rabbits in the forest
    static minNumberOfRabbits(answers, n)
    {
        // Initialize cnt variable
        var count = 0;
        // Initialize map
        var mp = new Map();
        for (var 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.has(answers[i]))
            {
                count += answers[i] + 1;
                mp.set(answers[i],answers[i] + 1);
            }
            if (mp.has(answers[i]))
            {
                mp.set(answers[i],mp.get(answers[i]) - 1);
            }
        }
        // count gives minimum number
        // of rabbits in the forest
        return count;
    }
    // Driver Code
    static main(args)
    {
        var arr = [10, 10, 0];
        var N = arr.length;
        // Function Call
        document.write(GFG.minNumberOfRabbits(arr, N));
    }
}
GFG.main([]);
</script>


Output

12

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



Last Updated : 18 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads