{"id":27607,"date":"2018-04-04T19:34:08","date_gmt":"2018-04-04T14:04:08","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27607"},"modified":"2018-04-04T19:34:08","modified_gmt":"2018-04-04T14:04:08","slug":"java-programming-count-distinct-elements-every-window-size-k","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-count-distinct-elements-every-window-size-k\/","title":{"rendered":"Java Programming &#8211; Count distinct elements in every window of size k"},"content":{"rendered":"<p>Given an array of size n and an integer k, return the of count of distinct numbers in all windows of size k.<span id=\"more-135172\"><\/span><\/p>\n<p>Example:<\/p>\n<pre>Input:  arr[] = {1, 2, 1, 3, 4, 2, 3};\r\n            k = 4\r\nOutput:\r\n3\r\n4\r\n4\r\n3\r\n\r\nExplanation:\r\nFirst window is {1, 2, 1, 3}, count of distinct numbers is 3\r\nSecond window is {2, 1, 3, 4} count of distinct numbers is 4\r\nThird window is {1, 3, 4, 2} count of distinct numbers is 4\r\nFourth window is {3, 4, 2, 3} count of distinct numbers is 3<\/pre>\n<p>An <strong>Efficient Solution<\/strong> is to use the count of previous window, while sliding the window. The idea is to create a hash map that stores elements of current widow. When we slide the window, we remove an element from hash and add an element. We also keep track of distinct elements. Below is algorithm.<\/p>\n<p>1) Create an empty hash map. Let hash map be hM<\/p>\n<p>2) Initialize distinct element count \u2018dist_count\u2019 as 0.<\/p>\n<p>3) Traverse through first window and insert elements of first window to hM. The elements are used as key and their counts as value in hM. Also keep updating \u2018dist_count\u2019<\/p>\n<p>4) Print \u2018dist_count\u2019 for first window.<\/p>\n<p>3) Traverse through remaining array (or other windows).<br \/>\n\u2026.a) Remove the first element of previous window.<br \/>\n\u2026\u2026.If the removed element appeared only once<br \/>\n\u2026\u2026\u2026\u2026..remove it from hM and do \u201cdist_count\u2013\u201d<br \/>\n\u2026\u2026.Else (appeared multiple times in hM)<br \/>\n\u2026\u2026\u2026\u2026..decrement its count in hM<\/p>\n<p>\u2026.a) Add the current element (last element of new window)<br \/>\n\u2026\u2026.If the added element is not present in hM<br \/>\n\u2026\u2026\u2026\u2026..add it to hM and do \u201cdist_count++\u201d<br \/>\n\u2026\u2026.Else (the added element appeared multiple times)<br \/>\n\u2026\u2026\u2026\u2026..increment its count in hM<\/p>\n<p>Below is implementation of above approach.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Program<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ An efficient Java program to count distinct elements in<br\/>\/\/ every window of size k<br\/>import java.util.HashMap;<br\/> <br\/>class CountDistinctWindow<br\/>{<br\/>    static void countDistinct(int arr[], int k)<br\/>    {<br\/>        \/\/ Creates an empty hashMap hM<br\/>        HashMap&lt;Integer, Integer&gt; hM =<br\/>                      new HashMap&lt;Integer, Integer&gt;();<br\/> <br\/>        \/\/ initialize distinct element  count for<br\/>        \/\/ current window<br\/>        int dist_count = 0;<br\/> <br\/>        \/\/ Traverse the first window and store count<br\/>        \/\/ of every element in hash map<br\/>        for (int i = 0; i &lt; k; i++)<br\/>        {<br\/>            if (hM.get(arr[i]) == null)<br\/>            {<br\/>                hM.put(arr[i], 1);<br\/>                dist_count++;<br\/>            }<br\/>            else<br\/>            {<br\/>               int count = hM.get(arr[i]);<br\/>               hM.put(arr[i], count+1);<br\/>            }<br\/>        }<br\/> <br\/>        \/\/ Print count of first window<br\/>        System.out.println(dist_count);<br\/> <br\/>        \/\/ Traverse through the remaining array<br\/>        for (int i = k; i &lt; arr.length; i++)<br\/>        {<br\/> <br\/>            \/\/ Remove first element of previous window<br\/>            \/\/ If there was only one occurrence, then<br\/>            \/\/ reduce distinct count.<br\/>            if (hM.get(arr[i-k]) == 1)<br\/>            {<br\/>                hM.remove(arr[i-k]);<br\/>                dist_count--;<br\/>            }<br\/>            else \/\/ reduce count of the removed element<br\/>            {<br\/>               int count = hM.get(arr[i-k]);<br\/>               hM.put(arr[i-k], count-1);<br\/>            }<br\/> <br\/>            \/\/ Add new element of current window<br\/>            \/\/ If this element appears first time,<br\/>            \/\/ increment distinct element count<br\/>            if (hM.get(arr[i]) == null)<br\/>            {<br\/>                hM.put(arr[i], 1);<br\/>                dist_count++;<br\/>            }<br\/>            else \/\/ Increment distinct element count<br\/>            {<br\/>               int count = hM.get(arr[i]);<br\/>               hM.put(arr[i], count+1);<br\/>            }<br\/> <br\/>           \/\/ Print count of current window<br\/>            System.out.println(dist_count);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Driver method<br\/>    public static void main(String arg[])<br\/>    {<br\/>        int arr[] =  {1, 2, 1, 3, 4, 2, 3};<br\/>        int k = 4;<br\/>        countDistinct(arr, k);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>3\r\n4\r\n4\r\n3<\/pre>\n<p>Time complexity of the above solution is O(n).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An Efficient Solution is to use the count of previous window, while sliding the window. The idea is to create a hash map that stores elements.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80128],"tags":[81829,81823,81822,81831,81830,81827,81820,81824,81825,81826,81828,81821,81819,81818,52264],"class_list":["post-27607","post","type-post","status-publish","format-standard","hentry","category-hashing","tag-moving-average-method","tag-rank-in-sql","tag-rank-over-partition-by","tag-slider-window","tag-sliding-window","tag-sliding-window-algorithm","tag-sliding-window-in-networking","tag-sliding-window-protocol-program-in-c","tag-sliding-window-protocol-program-in-java","tag-sql-analytic-functions","tag-tcp","tag-tcp-frame-format","tag-tcp-packet-format","tag-tcp-sliding-window","tag-windows-partition"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27607","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27607"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27607\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27607"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27607"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27607"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}