{"id":1855,"date":"2024-02-05T13:00:00","date_gmt":"2024-02-05T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1855"},"modified":"2024-03-06T11:56:23","modified_gmt":"2024-03-06T11:56:23","slug":"rabbits-in-forest-problem","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/rabbits-in-forest-problem\/","title":{"rendered":"Rabbits in Forest Problem Solved (C++, Java, Python)"},"content":{"rendered":"\n<p>Counting the frequency of the numbers in an array can be done by maps. The map is a data structure that stores key and value pairs. It helps you to easily count the frequency, to get value from the key, etc. In this article, we will discuss the famous leetcode problem called the Rabbits in Forest.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Rabbits in Forest Problem Explained<\/strong><\/h2>\n\n\n\n<p><strong>In the Rabbits in Forest problem, we are given an array that contains some rabbits&#8217; answers to the question, \u201cHow many rabbits have the same color as yours\u201d. We have to count the minimum number of rabbits present in the forest.<\/strong> <\/p>\n\n\n\n<p>Note that the Array size may be less than the total number of rabbits. Let\u2019s understand this with an example:<\/p>\n\n\n\n<p><strong>Input:<\/strong>&nbsp; [0, 2, 1, 1]<\/p>\n\n\n\n<p><strong>Output:<\/strong> 6<\/p>\n\n\n\n<p>The answer will look like this:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/CvJkUwLjufvzAFHZqE5ktI8rcbVsB73XMss_yHRTzRcHx_qVyAh0cT3C9oHa5t1zwfW7Ehv6YRlCrUCPWtr6IPyV8YA2IRaILxwKrOb145IiHL9UQVfhTG_gTfBPujwifxcWCAHEf-lvKeg1hKexag0\" alt=\"Initial Array\"\/><\/figure>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First rabbits say 0, which means no rabbits have the same color as him. Let&#8217;s assume his color is white so the total number of white rabbits in the forest is 1.<\/li>\n\n\n\n<li>The second rabbit says 2, let\u2019s assume his color is brown which means 2 more rabbits are having the color brown.<\/li>\n\n\n\n<li>The third one says 1, which means this rabbit has a different color than brown and white because if this color is brown, he also sees 2 brown rabbits. If his color is white then there will be two rabbits in the forest having color white. So its color will be different than brown and white. Let\u2019s assume the color is green. So there will be 2 green rabbits.<\/li>\n\n\n\n<li>The fourth one says 1, it cannot be brown and white as discussed, So let us assume his color is green then it must see one more green rabbit as the green rabbit count is 2.<\/li>\n\n\n\n<li>So the total number of rabbits is 1 white + 3 brown + 2 green&nbsp; = 6.<\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/C0EiXcJFT7spTyYjw2mkUdxMjI7e5BtL8-X84vI06AXi3LZHDFr-I0VeamqeygMAFIkmICCMiQJ-Lf-iXy0j4dNgfQhRjA81KgYjzHe8MOHdbYuoj9TGpsZhQWPeRx7gTmHS6vO2bfcwhWN9T9FXaXA\" alt=\"Result of Rabbits in Forest problem\"\/><\/figure>\n\n\n\n<p>Another similar question about removing duplicate elements from an array, a <a href=\"https:\/\/favtutor.com\/articles\/4-sum-problem\/\">4-sum problem<\/a>, etc., using a map. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Hash Map Approach<\/strong><\/h2>\n\n\n\n<p>Let&#8217;s assume you have an array [1, 1, 1, 1], which means you have 2 rabbits of the same color white, and 2 rabbits of the same color green. This can also be observed by finding the number of rabbits with the same value as a[i]. <\/p>\n\n\n\n<p>Now, find their remainder when you divide this count by a[i]+1. Add this remainder to the count. Then, add the count to the answer variable.<\/p>\n\n\n\n<p>Let&#8217;s take an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Q74gFvp2ypDQvI3DYAl-WXXzZI9cP_kHuyYR1BlBJnSjxGhFvnGD725A5KIoROyCRluiewg132T_Q0aTtriKSwlZpO7kEMvFPqIZ53pOgc6fjSbX4cN5jiewyVfGqeWaQm95xQw0wVbmYMNMuxhgz6s\" alt=\"Hash Map Approach\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create an unordered_map that stores the frequency of each value in the array.<\/li>\n\n\n\n<li>Iterate over the map and check how many extra rabbits are required that are not in the array by calculating the remainder.<\/li>\n\n\n\n<li>Add this remainder into the frequency and add this frequency into the ans variable.<\/li>\n\n\n\n<li>Return the ans variable.<\/li>\n<\/ul>\n\n\n\n<p>The time complexity for the above process is O( n log(n) ) as we are storing the value into the map which requires log(n) time complexity. We are iterating over the loop that took O(n) time complexity.\u00a0The space complexity will be O(n) as we are storing values on the map.<\/p>\n\n\n\n<p>You can also <a href=\"https:\/\/favtutor.com\/blogs\/intersection-of-two-arrays-using-hashmap\">find the intersection of two arrays<\/a> using hashmap.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimize <strong>Sorting<\/strong> Approach<\/strong><\/h2>\n\n\n\n<p>As mentioned above, we are using O(n) space complexity to store all the values in the array. This can be reduced if we sort the array and count the values till they are the same and then find the remainder. In that case, we do not have to store the values in the map and our space will reduce to O(1).<\/p>\n\n\n\n<p>Let\u2019s examine this approach:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Sort the given array.<\/li>\n\n\n\n<li>Create a variable count that stores the frequency of the same value in the array<\/li>\n\n\n\n<li>Iterate over the array and keep increasing the count with 1 if the value of the current index is equal to the value at the next index.<\/li>\n\n\n\n<li>If values are not the same, then find the remainder of this count with the current value of the array i.e. count % (a[i] + 1).<\/li>\n\n\n\n<li>Add this remainder into the count variable and this count into the ans variable.<\/li>\n\n\n\n<li>Again update the count to 1 and continue the same process.<\/li>\n\n\n\n<li>Return the ans once the loop is over.<\/li>\n<\/ol>\n\n\n\n<p>Let\u2019s examine the code for the above process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the solution implemented in C++ for Rabbits in Forest problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint main(){\n\n    vector&lt;int&gt; arr = {1, 1, 2, 0, 1};\n    \/\/ sort the given array\n    sort(arr.begin(), arr.end());\n\n    \/\/ count variable for count the frequency of the same elements.\n    int count  = 1;\n    \/\/ ans variable which stores total rabbits and n stores the size of the array.\n    int ans = 0, n = arr.size();\n\n    for(int i=0; i&lt;arr.size(); i++ ){\n        \n        if(i == arr.size()-1 || (arr[i]!=arr[i+1])){\n            \/\/ find remainder.\n            int rem = count%(arr[i]+1);\n            if(rem) ans = ans + (arr[i]+1) - rem;\n            count = 1;\n        }else{\n            \/\/ if current and next values are not same increment our count variable.\n            count = count + 1;\n        }\n    }\n    \n    ans = ans + n;\n    cout&lt;&lt;ans&lt;&lt;endl;\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>We can program it with Java also:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass RabbitsInForest {\n    public static void main(String[] args) {\n        List&lt;Integer&gt; arr = new ArrayList&lt;&gt;(Arrays.asList(1, 1, 2, 0, 1));\n        \n        \/\/ Sort the given array\n        Collections.sort(arr);\n\n        \/\/ Count variable for counting the frequency of the same elements.\n        int count = 1;\n        \/\/ Ans variable which stores total rabbits and n stores the size of the array.\n        int ans = 0;\n        int n = arr.size();\n\n        for (int i = 0; i &lt; arr.size(); i++) {\n            if (i == arr.size() - 1 || arr.get(i) != arr.get(i + 1)) {\n                \/\/ Find remainder.\n                int rem = count % (arr.get(i) + 1);\n                if (rem != 0) ans += (arr.get(i) + 1) - rem;\n                count = 1;\n            } else {\n                \/\/ If current and next values are not same increment our count variable.\n                count++;\n            }\n        }\n\n        ans += n;\n        System.out.println(ans);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Below is the Python program for the sorting approach:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">arr = [1, 1, 2, 0, 1]\n\n# Sort the given array\narr.sort()\n\n# Count variable for counting the frequency of the same elements.\ncount = 1\n# Ans variable which stores total rabbits and n stores array size.\nans = 0\nn = len(arr)\n\nfor i in range(len(arr)):\n    if i == len(arr) - 1 or arr[i] != arr[i + 1]:\n        # Find remainder.\n        rem = count % (arr[i] + 1)\n        if rem:\n            ans += (arr[i] + 1) - rem\n        count = 1\n    else:\n        # If current and next values are not same increment our count variable.\n        count += 1\n\nans += n\nprint(ans)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-3be54abb02b685191decfc1c1c5e797e\" style=\"background-color:#fedcba\"><code>8<\/code><\/pre>\n\n\n\n<p><strong>The time complexity for the Sorting approach to solving the Rabbits in Forest problem is O( n log(n) ).<\/strong> We are iterating over a loop whose time complexity does O ( n ) so overall complexity becomes O( n log(n) ).\u00a0Space complexity will be reduced to O(1) as no extra space is used.\u00a0<\/p>\n\n\n\n<p>We can compare both the approaches to see how we optimized it:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><strong>Approach<\/strong><\/th><th><strong>Time Complexity<\/strong><\/th><th><strong>Space Complexity<\/strong><\/th><th><strong>Description<\/strong><\/th><\/tr><\/thead><tbody><tr><td>&nbsp; &nbsp; Hash Map Approach<\/td><td>&nbsp; &nbsp; O( n log(n) )<\/td><td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; O(n)<\/td><td>Inserting values into the hash map requires O( log(n) ) time.<\/td><\/tr><tr><td>&nbsp; &nbsp; Optimized Approach<\/td><td>&nbsp; &nbsp; O( n log(n) )<\/td><td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; O(1)<\/td><td>As we are using a sorting operation in O( n log(n) ) time.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we learned about hash maps and sorting functions to solve the Rabbits in Forest problem from <a href=\"https:\/\/leetcode.com\/problems\/rabbits-in-forest\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. Some of the similar programming problems you can solve are the <a href=\"https:\/\/favtutor.com\/articles\/majority-element\/\">Majority Element problem<\/a>, <a href=\"https:\/\/favtutor.com\/articles\/valid-anagram\/\">Valid Anagram<\/a>, or <a href=\"https:\/\/favtutor.com\/articles\/alien-dictionary-problem\/\">Alien Dictionary problem<\/a>, to brush up your skills.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will solve the Rabbits in Forest problem from leetcode, using hashmap or sorting with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":1857,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1855","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1855","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1855"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1855\/revisions"}],"predecessor-version":[{"id":2212,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1855\/revisions\/2212"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1857"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1855"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1855"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1855"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}