<?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[Algorist Weekly - Medium]]></title>
        <description><![CDATA[An interesting algorithm per week - Medium]]></description>
        <link>https://medium.com/algorist-weekly?source=rss----9859f48babe0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Algorist Weekly - Medium</title>
            <link>https://medium.com/algorist-weekly?source=rss----9859f48babe0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:17:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/algorist-weekly" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Merging Communities]]></title>
            <link>https://medium.com/algorist-weekly/merging-communities-6f72b1c0d3a2?source=rss----9859f48babe0---4</link>
            <guid isPermaLink="false">https://medium.com/p/6f72b1c0d3a2</guid>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Rupesh Sasne]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 07:48:08 GMT</pubDate>
            <atom:updated>2019-08-01T03:54:30.770Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered how Facebook/LinkedIn learns whether two people may know each other through some common friends? Read on to know the answer… 😉</p><p>I came across this problem statement while practicing the problem-solving at HackerRank;</p><p><a href="https://www.hackerrank.com/challenges/merging-communities/problem">Merging Communities | HackerRank</a></p><p>So, there were two types of queries, M &amp; Q.</p><ol><li>M I J =&gt; communities containing person I &amp; J merged (if they belong to different communities).</li><li>Q =&gt; print the size of the community to which the person belongs.</li></ol><p>The algorithms were pretty obvious, merge the two different communities &amp; return the size of the community whenever requested.</p><p><strong>Merge</strong></p><pre>merge(i, j)<br>    ci = community(i)<br>    cj = community(j)<br>    <br>    if (ci == cj) return</pre><pre>    mergeCommunities(ci, cj)</pre><ol><li>Maintain a list of sets.</li><li>Initially, each person will be in its own community represented by a set.</li><li>For merging communities of p1 &amp; p2, search in the list to get respective community sets. If both the sets are different then only merge them and clear one of them.</li></ol><p><strong>Query</strong></p><pre>query(i)<br>    ci = community(i)<br>    return ci.size()</pre><ol><li>Search across the list to get the community set for the query person</li><li>Return the size</li></ol><p>That seemed pretty good, initially :). So I implemented the above algorithms as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68942ff319db9e16ce9341c31fc66e48/href">https://medium.com/media/68942ff319db9e16ce9341c31fc66e48/href</a></iframe><p>I did some dry runs, ran the sample tests; it worked great up until the moment I submitted it.</p><p>It gave me the TLE verdict. 🤦‍♂</p><p>I should have expected this, the verdict TLE was obvious as the time complexity of this naive algorithm is O(n*q) where the input size is 1 ≤ n ≤ 10⁵ &amp; 1 ≤ q ≤ 2*10⁵.</p><p>“How can I improve it?”, I gave it a thought.</p><p>I had to design an efficient data structure for merge such that the searching will be better than O(n), and what is better than that? O(log n), isn’t it?</p><p>What if I’d connect two persons P1 &amp; P2 (and hence their communities) via some common ancestor? In other words, what if I’d put P1 &amp; P2 in an n-ary tree? And initially, every node acts as the root of its own community with size 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*DuTpI47PHVCeWzO1_nEglw.png" /><figcaption><em>Merging communities via a common ancestor</em></figcaption></figure><p>In this case, if we maintain a hash of each person, searching for the person will require O(1) &amp; finding a root of its community will take O(log n)</p><p><strong>Proposition</strong>: Depth of any node x is at most log N.</p><p>Let’s modify the Merge &amp; Query algorithms</p><p><strong>Merge</strong></p><pre>merge(p1, p2)<br>    p1Root = root(p1)<br>    p2Root = root(p2)<br>    <br>    if (p1Root == p2Root) return</pre><pre>    p2.parent = p1<br>    p1.size += p2.size</pre><pre>root(p1)<br>    traverse till root using parent pointer; root is the node which<br>    doesn&#39;t have a parent (or which is pointing to self as parent)</pre><p>Query</p><pre>query(p)<br>    pRoot = root(p)<br>    return pRoot.size()</pre><p>And, here is the implementation; not providing the main method for brevity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23296d3fb7a37a58708880108df2da60/href">https://medium.com/media/23296d3fb7a37a58708880108df2da60/href</a></iframe><p>That also seemed pretty good, at least better than before.</p><p>I ran the sample tests, it worked great; up until the moment I submitted it.</p><p>It gave me a TLE verdict, again!!! ⏰</p><p>But it was definitely better than the first solution, only 3 tests were failing this time due to timeout. I had to find out what was going wrong. The time complexity had been reduced to O(n + q*log n) from O(q*n); still, it was giving a TLE verdict.</p><p>“Is there any scope for improvement?” 🤔</p><p>Had I really achieved O(n + q*log n)? Let’s get back to the diagram <em>Merging communities via a common ancestor</em>, in the second step for merging p2 &amp; p6 what if we’d have made p6 as the parent of the root of p2? In other words, merge large community in the smaller community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*DngACy-7hgJl4JDOVx31sg.png" /><figcaption>Merging larger communities in smaller ones</figcaption></figure><p>If we keep doing this one can clearly see the height of the tree will grow dramatically. I hadn’t considered this scenario in the implementation and that&#39;s why the algorithm performed O(q*n) in the worst case?</p><p>So I guarded the merge algorithm as follows; the idea was to merge smaller communities into the larger ones to keep height maintained.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32df140d72ae2a98c769650adf4ea380/href">https://medium.com/media/32df140d72ae2a98c769650adf4ea380/href</a></iframe><p>That seemed pretty good, I ran the sample tests, and it worked great after submitting also 😅.</p><p>The complexity is O(n + q*log n)</p><p>Now the question, How to know if two persons are connected, that too in O(log n) time?</p><pre>connected(p1, p2) = root(p1) == root(p2)</pre><p>The algorithm which I used is called as;</p><blockquote><strong>Union-Find (Disjoint Sets)</strong></blockquote><p>One can optimize the above implementation further by compressing the path to the root node. How? Think and let me know in the comments.</p><p><strong>References</strong></p><ul><li><a href="https://www.coursera.org/learn/algorithms-part1">Algorithms, Part I</a></li><li><a href="https://algs4.cs.princeton.edu/home/">Algorithms, 4th Edition</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f72b1c0d3a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/algorist-weekly/merging-communities-6f72b1c0d3a2">Merging Communities</a> was originally published in <a href="https://medium.com/algorist-weekly">Algorist Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>