<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Competitive Programming - Medium]]></title>
        <description><![CDATA[A guide to the competitive programming - Medium]]></description>
        <link>https://medium.com/competitive-programming?source=rss----e76460717e7f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Competitive Programming - Medium</title>
            <link>https://medium.com/competitive-programming?source=rss----e76460717e7f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:46:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/competitive-programming" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Leetcode 401: Binary Watch]]></title>
            <link>https://medium.com/competitive-programming/leetcode-401-binary-watch-e65f005a52e3?source=rss----e76460717e7f---4</link>
            <guid isPermaLink="false">https://medium.com/p/e65f005a52e3</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Bhargav Jhaveri]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 22:28:54 GMT</pubDate>
            <atom:updated>2017-03-22T14:44:51.417Z</atom:updated>
            <content:encoded><![CDATA[<p>Leetcode 401: Binary Watch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F_tPXDjB6n3PsyGnRpjCg.jpeg" /><figcaption>Image credit: <a href="https://unsplash.com/@veri_ivanova">Veri Ivanova</a> from <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>“A binary watch has 4 LEDs on the top which represent the <strong>hours</strong> (<strong>0–11</strong>), and the 6 LEDs on the bottom represent the <strong>minutes</strong> (<strong>0–59</strong>).</p><p>Each LED represents a zero or one, with the least significant bit on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*50_zSO55OUMdaRSU.jpg" /></figure><p>For example, the above binary watch reads “3:25”.</p><p>Given a non-negative integer <em>n</em> which represents the number of LEDs that are currently on, return all possible times the watch could represent.</p><p><strong>Example:</strong></p><pre>Input: n = 1<br>Return: [&quot;1:00&quot;, &quot;2:00&quot;, &quot;4:00&quot;, &quot;8:00&quot;, &quot;0:01&quot;, &quot;0:02&quot;, &quot;0:04&quot;, &quot;0:08&quot;, &quot;0:16&quot;, &quot;0:32&quot;]</pre><p><strong>Note:</strong></p><ul><li>The order of output does not matter.</li><li>The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.</li><li>The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.</li></ul><h3>Solution:</h3><p>Problem is simple to understand. We get “num” as an argument and we have to find out all the possible times which can be formed using this.</p><p>With input value num as 1 we can generate</p><pre>[&quot;1:00&quot;, &quot;2:00&quot;, &quot;4:00&quot;, &quot;8:00&quot;, &quot;0:01&quot;, &quot;0:02&quot;, &quot;0:04&quot;, &quot;0:08&quot;, &quot;0:16&quot;, &quot;0:32&quot;]</pre><p>Now, let’s try to formulate the solution.</p><p>We have to find all the possible places where we can set the bit. Hour bit can be set to 1/2/4/8. Minute bit can be set to 1/2/4/8/16/32.</p><p>If we have num as 2, more combinations are possible. So, trying to solve the problem in straightforward way looks a bit complicated. So, let’s think of another approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLk5mKlcdVwHPjwHAOmjUA.jpeg" /></figure><ol><li>Iterate over all the possible hour and minute options.</li><li>For each option, find the number of set bits in hour and minute.</li><li>If the “number of set bit” is equal to “num” — bingo! We have found a candidate. Find all such candidates and add them to a list.</li></ol><pre>public List&lt;String&gt; readBinaryWatch(int num) {<br>        <br>        List&lt;String&gt; ans = new ArrayList&lt;&gt;();<br>        <br>        <br>        // Hours iterate from 0-11 and<br>        // Minutes iterate from 0-59.<br> <br>        // See for which values, number of 1&#39;s match<br>        // with the value &lt;num&gt; provided.<br>        <br>       for(int h=0; h&lt;12; h++) {<br>            <br>           for(int m=0; m&lt;60; m++) {<br>                <br>                // Number of set bits in hour portion and in minute<br>                // part has to be equal to num.</pre><pre>                if(Integer.bitCount(h) <br>                                  + Integer.bitCount(m) == num) {<br>                    ans.add(String.format(&quot;%d:%02d&quot;,h,m));<br>                }<br>                <br>            }<br>            <br>        }<br>        <br>        return ans;<br>    }</pre><p>Time complexity: O(1)</p><p>Space complexity: O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e65f005a52e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/competitive-programming/leetcode-401-binary-watch-e65f005a52e3">Leetcode 401: Binary Watch</a> was originally published in <a href="https://medium.com/competitive-programming">Competitive Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 347: Top K Frequent Elements]]></title>
            <link>https://medium.com/competitive-programming/leetcode-347-top-k-frequent-elements-274c42b5f69b?source=rss----e76460717e7f---4</link>
            <guid isPermaLink="false">https://medium.com/p/274c42b5f69b</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Bhargav Jhaveri]]></dc:creator>
            <pubDate>Sat, 18 Mar 2017 01:49:21 GMT</pubDate>
            <atom:updated>2017-03-22T14:47:16.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVvY0gWRMitj3a-eyei4Qw.jpeg" /></figure><p>“Given a non-empty array of integers, return the <strong><em>k</em></strong> most frequent elements.</p><p>For example,<br>Given [1,1,1,2,2,3] and k = 2, return [1,2].”</p><p>“<strong>Note:</strong></p><ul><li>You may assume <em>k</em> is always valid, 1 ≤ <em>k</em> ≤ number of unique elements.</li><li>Your algorithm’s time complexity <strong>must be</strong> better than O(<em>n</em> log <em>n</em>), where <em>n</em> is the array’s size.”</li></ul><p>Here is my take on the problem:</p><p>We are supposed to solve the problem in Time Complexity better than O(<em>nlgn</em>).</p><p>If that constraint were not present, here is what can be done.</p><ol><li>Use Map (Dictionary) and store the frequency of the number.</li><li>Sort the map by values.</li><li>Pick only first k objects.</li></ol><p>But since, the constraint is present, we can use the following algorithm:</p><p>Sample input: [1,1,1,2,2,3] and k = 2</p><ol><li>Use map/dictionary and store the frequency of the number and maximum frequency of all the numbers. <br>So at the end of this operation, for the sample problem, map would look like this: 1 → 3, 2 → 2, 3 →1. Also, maximum frequency will be 3.</li><li>Now, since, we cannot use regular sorting approach, another thing that comes to mind is, bucket sort.</li><li>Create a multi-storage bucket with (maximum frequency + 1)as its size. Now, based on frequency of the word, put it in the appropriate bucket level. In our example, Put 1 at level 3, put 2 at level 2 and put 3 at level 1.</li><li>There might be more than one numbers with the same frequency. So, we can use linked list to store more than one elements at the same level.</li><li>Now, iterate over the bucket elements and keep a counter to match with the input value k.</li></ol><pre>public List&lt;Integer&gt; topKFrequent(int[] nums, int k) {<br>        <br>        int len = nums.length;<br>        int maxFreq = 0;<br>        <br>        // Algo - step 1:     </pre><pre>        Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>        <br>        for(int i=0; i&lt;len; i++) {<br>            map.put(nums[i], map.getOrDefault(nums[i],0) + 1);<br>            <br>            maxFreq = Math.max(maxFreq, map.get(nums[i]));<br>        }<br>        <br>        // Algo - step 3 and 4: Create bucket of size of max Freq. <br>        <br>        List&lt;Integer&gt; [] bucketList = new LinkedList[maxFreq+1];<br>        <br>        for(int i=0; i&lt;= maxFreq; i++) {<br>            bucketList[i] = new LinkedList&lt;&gt;();<br>        }<br>        <br>        // Put elements in the bucket by iterating over the map.<br>        for(Integer key : map.keySet()) {<br>            <br>            int freq = map.get(key);<br>            <br>            bucketList[freq].add(key);<br>            <br>        }<br>  <br>        // Algo step 5:       </pre><pre>        int ct = 0;<br>        List&lt;Integer&gt; ans = new LinkedList&lt;&gt;();<br>        <br>        for(int i=maxFreq; i&gt;=0; i--) {<br>                <br>            List&lt;Integer&gt; currentList = bucketList[i];<br>            <br>            for(Integer j: currentList) {<br>                if(ct &lt; k) {<br>                    ans.add(j);   <br>                    ct++;<br>                } else {<br>                    return ans;<br>                }<br>            }    <br>            <br>        }<br>        <br>        return ans;<br>        <br>        <br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=274c42b5f69b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/competitive-programming/leetcode-347-top-k-frequent-elements-274c42b5f69b">Leetcode 347: Top K Frequent Elements</a> was originally published in <a href="https://medium.com/competitive-programming">Competitive Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 451: Sort Characters By Frequency]]></title>
            <link>https://medium.com/competitive-programming/leetcode-451-sort-characters-by-frequency-873f876de315?source=rss----e76460717e7f---4</link>
            <guid isPermaLink="false">https://medium.com/p/873f876de315</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Bhargav Jhaveri]]></dc:creator>
            <pubDate>Wed, 15 Mar 2017 22:55:54 GMT</pubDate>
            <atom:updated>2017-03-22T14:46:02.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*C30EKTXzHC_ETciZ_g5Q7A.jpeg" /></figure><h3>Sort Characters By Frequency</h3><pre>Given a string, sort it in decreasing order based on the frequency of characters.</pre><pre><strong>Example:</strong></pre><pre><strong>Input:</strong><br>&quot;tree&quot;<br><br><strong>Output:</strong><br>&quot;eert&quot;<br><br><strong>Explanation:</strong><br>&#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once.<br>So &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer.</pre><pre><strong>Input:</strong><br>&quot;cccaaa&quot;<br><br><strong>Output:</strong><br>&quot;cccaaa&quot;<br><br><strong>Explanation:</strong><br>Both &#39;c&#39; and &#39;a&#39; appear three times, so &quot;aaaccc&quot; is also a valid answer.<br>Note that &quot;cacaca&quot; is incorrect, as the same characters must be together.</pre><h3>Here is my understanding and solution to the problem</h3><p>One approach is to use HashMap — sort the map by values. Time complexity of this code will be O(nlgn)</p><p>Here is another approach. This is based on counting sort or bucket sort. Time complexity of this approach would be O(n).</p><p>Algorithm is as follows:</p><p>Sample input string : cwcwcrtr</p><p>Step 1: Store freq of each character. c — 3, r — 2, w — 2, t — 1</p><p>Step 2: Prepare multi storage bucket. With each storage level — characters with same frequency.</p><p>Step 3: bucket[3] = c , bucket[2] = rw , bucket[1] = t</p><p>Step 4: Merge elements with same freq in final ans.</p><p>Step 5: Ans: cccrrwwt</p><pre>public String frequencySort(String s) {<br><br><br>    int len = s.length();</pre><pre>    // Assuming Extended ASCII encoding.<br>    int[] freq = new int[256];<br><br>    // Step 1: Store freq of each character. c:3, r:2, w:2, t:1<br>    // And finding max vertical bucket levels.</pre><pre>    int bucketLevel = 0;<br>    for (int i = 0; i &lt; len; i++) {<br>        freq[s.charAt(i)]++;<br><br>        bucketLevel = Math.<em>max</em>(bucketLevel, freq[s.charAt(i)]);<br>    }<br><br>    // Step 2: Prepare multi storage bucket. <br>    // With each storage level characters with same frequency.</pre><pre>    StringBuilder[] bucketBuilder = <br>                                new StringBuilder[bucketLevel + 1];<br><br>    for (int i = 0; i &lt; bucketBuilder.length; i++) {<br>        bucketBuilder[i] = new StringBuilder();<br>    }</pre><pre>    // Step 3: bucket[3] = c , bucket[2] = rw , bucket[1] = t<br>    for (int i = 0; i &lt; 256; i++) {<br><br>        int elemFreq = freq[i];<br>        if (elemFreq &gt; 0) {<br>            bucketBuilder[elemFreq].<br>                           append(Character.<em>toString</em>((char) (i)));<br>        }<br><br>    }<br><br>    // Step 4: Merge elements with same freq/bucket level in ans.</pre><pre>    StringBuilder ans = new StringBuilder();<br>    for (int i = bucketLevel; i &gt; 0; i--) {<br><br>        char[] levelChars = bucketBuilder[i].<br>                                       toString().toCharArray();<br><br>        for (int j = 0; j &lt; levelChars.length; j++) {<br><br>            for (int k = 0; k &lt; i; k++) {<br>                ans.append(levelChars[j]);<br>            }<br><br>        }<br><br>    }<br><br>    return ans.toString();<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873f876de315" width="1" height="1" alt=""><hr><p><a href="https://medium.com/competitive-programming/leetcode-451-sort-characters-by-frequency-873f876de315">Leetcode 451: Sort Characters By Frequency</a> was originally published in <a href="https://medium.com/competitive-programming">Competitive Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>