<?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[Stories by Ruthreshwar Gajendiran on Medium]]></title>
        <description><![CDATA[Stories by Ruthreshwar Gajendiran on Medium]]></description>
        <link>https://medium.com/@ruthreshwar?source=rss-248fa955a348------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L94Q_e4YS8AHQKKI</url>
            <title>Stories by Ruthreshwar Gajendiran on Medium</title>
            <link>https://medium.com/@ruthreshwar?source=rss-248fa955a348------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:54:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ruthreshwar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[Algorithm] Diagonal traversal of matrix]]></title>
            <link>https://ruthreshwar.medium.com/algorithm-diagonal-traversal-of-matrix-0c468110d10a?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c468110d10a</guid>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 22:44:42 GMT</pubDate>
            <atom:updated>2023-11-22T22:44:42.290Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Question:</strong></p><p>A 2D integer array is provided, return all the elements in diagonal order.</p><p>[1, 2, 3]</p><p>[4, 5, 6]</p><p>[7, 8, 9]</p><p><strong>Output:</strong> 1,4,2,7,5,3,8,6,9</p><p><strong>Solution:</strong></p><p><strong>Points to note:</strong></p><ol><li>Sum of <strong>row index + column index </strong>will be same for the diagonal in a matrix.</li></ol><p><strong>Algorithm:</strong></p><p><strong>Step 1:</strong> Define a List of List to store the diagonal</p><p><strong>Step 2:</strong> Use two for loops to iterate the 2D matrix</p><p><strong>Step 3:</strong> Calculate the diagonal value by adding <strong>row index + column index</strong></p><p><strong>Step 4:</strong> For each index value insert values in the list. If the index value is greater than size then create new list and add it.</p><p><strong>Step 5:</strong> Convert List of List to int array and return</p><p><strong>Code:</strong></p><pre>class Test {<br>    public int[] getDiagonalElements(List&lt;List&lt;Integer&gt;&gt; nums) {<br>        int count = 0; <br>        List&lt;List&lt;Integer&gt;&gt; lists = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            List&lt;Integer&gt; row = nums.get(i);<br><br>            for (int j = 0; j &lt; row.size(); j++) {<br>                int idx = i + j;<br><br>                if (lists.size() &lt; idx + 1) {<br>                    lists.add(new ArrayList&lt;&gt;());<br>                }<br>                lists.get(idx).add(row.get(j));<br>                <br>                count ++;<br>            }<br>        }<br><br>        int[] res = new int[count];<br>        int idx = 0;<br>        for (List&lt;Integer&gt; list : lists) {<br>            for (int i = list.size() - 1; i &gt;= 0; i--) {<br>                res[idx++] = list.get(i); <br>            }<br>        }<br>        return res;<br>    }<br>}<br></pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c468110d10a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Algorithm] Count nice pairs in an array]]></title>
            <link>https://ruthreshwar.medium.com/algorithm-count-nice-pairs-in-an-array-33e60a46b749?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/33e60a46b749</guid>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 22:32:47 GMT</pubDate>
            <atom:updated>2023-11-21T22:33:41.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello,</p><p>Here you will find the algorithm and tips to solve the problem.</p><p><strong>Question:</strong></p><p>You are given an array nums that consists of non-negative integers. Find all pairs that satisfy the below equation<br><strong>nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) </strong>with condition</p><p><strong>0 &lt;= i &lt; j &lt; nums.length</strong><br>Since that number can be too large, return it modulo 10^9 + 7.</p><p><strong>Solution:</strong></p><p><strong>Points to note:</strong></p><ol><li>The equation. If you observe the equation it works with value i and j on both sides. Lets change the equation like below so it will be easy for our computation with only one iteration. <strong><em>nums[i] + rev(nums[i]) == nums[j] + rev(nums[j])</em></strong></li><li>Second is to note the condition. For finding the pairs the value of i should be less than j. (<strong>i &lt; j)</strong></li><li>Third point to note is the modulo result. It is explicitly mentioned that the number of pairs can be too large so the output should be the modulo value.</li></ol><p><strong>Algorithm:</strong></p><p><strong>Step 1:</strong> Initialise values to store <strong>pair count</strong> and <strong>hash map</strong> to store the number of occurrences</p><p><strong>Step 2:</strong> Create a method to reverse the integer</p><blockquote>while (num &gt; 0) {</blockquote><blockquote>reverse = (reverse * 10) + (num%10);</blockquote><blockquote>num = num/10; }</blockquote><p><strong>Step 3: </strong>Iterate the given array in reverse order</p><p>* Since i &lt; j we should try finding the pairs in reverse order.</p><p><strong>Step 4:</strong> Apply formula and check if the value is available in hash map</p><p><strong><em>nums[i] + rev(nums[i]) == nums[j] + rev(nums[j])</em></strong></p><p><strong>Step 4.1:</strong> If value is present get the value and add to the pair count (take modulo here because the result can exceed the int range) and increment the value of the hash map.</p><p><strong>Step 4.2:</strong> If the value is null add the key and value 1 to hash map.</p><p><strong>Step 5:</strong> Close the for loop and return pair count.</p><p><strong>Code:</strong></p><pre>class Solution {<br>    public int countNicePairs(int[] nums) {<br>        int pair = 0;<br>        Map&lt;Integer, Integer&gt; values = new HashMap&lt;Integer, Integer&gt;();<br>        int MOD = 1000000007;<br>        for (int i = nums.length - 1 ; i &gt;= 0; i--) {<br>            int value = nums[i] - rev(nums[i]);<br>            if (values.get(value) != null) {<br>                pair = (pair + values.get(value))%MOD;<br>                values.put(value, values.get(value)+1);<br>            } else {<br>                values.put(value, 1);<br>            }<br>        }<br>        return pair;<br>    }<br><br>    public int rev(int num) {<br>        int reverse = 0;<br>        while (num &gt; 0) {<br>            reverse = (reverse * 10) + (num%10);<br>            num = num/10;<br>        }<br>        return reverse;<br>    } <br>}</pre><p>Thanks for reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33e60a46b749" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bazel vs Maven]]></title>
            <link>https://ruthreshwar.medium.com/bazel-vs-maven-8fc32308dba7?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc32308dba7</guid>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[bazel]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 16:01:57 GMT</pubDate>
            <atom:updated>2021-12-29T16:01:57.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the years, I have always used Maven or Gradle for dependency management. Why? Because it is very easy to understand and maintain Maven. I had different questions when I first learned about Bazel.</p><ol><li>Why do we need Bazel when Maven works like a charm?</li><li>Bazel avoids “Dependency Hell” — We have an option to exclude a version that conflicts with other dependencies. What does Bazel do that’s simpler than this?</li><li>We have centralised repositories where Maven artifacts can be stored and distributed. How do I manage external dependencies using Bazel?</li><li>Maven has very minimal configuration (mostly it is only the pom.xml (Project Object Model) and project structure) but when I look at Bazel it has a lot of complex configurations. Is it really worth it to even start with Bazel?</li><li>We have git submodules concept to link project to specific commit version internally. Why do we require Bazel?</li></ol><p>Do you also feel the same way? If you have more questions, feel free to add in the comments below. I had these questions when there were talks about migrating from Maven to Bazel.</p><p>As someone who has used Maven for over ten years, Bazel was easy for me to understand when I started comparing Bazel and Maven. It became clear to me that the intent for both are different.</p><p>Let me try to explain the answers for the questions I posted above. This writeup will help you to understand what is Bazel in comparison to Maven.</p><p><strong>Question 1: Why do we need Bazel when Maven is working like a charm?</strong></p><p>Maven downloads all dependencies for the project, compiles the source code, performs operation like documentation and any maven plugin task and finally creates a package. It basically makes our build process smooth.</p><p>Say you have a mono repository with multiple services or multiple components. Some drawbacks of maven here is</p><p><strong>MAVEN</strong>: Once a library in the mono repository is updated every client has to upgrade to the latest version.</p><p>Say for example in a mono repo if a project is using their service client version 1.0 and service client is introducing new changes in 1.1 all the projects using service client 1.0 has to update to 1.1 to use the new features. Few projects may decide to stick to an older version, as they don’t see any pressing need for the update.</p><p><strong>BAZEL</strong>: It is best suited for mono repositories. Bazel doesn’t depend on generated artifacts, but it depends directly on the commit. When Bazel updates the commit all modules gets updated code.</p><p><strong>MAVEN</strong>: Build process is slow since it takes time to download all the external dependencies. For a mono repo you may have to download all the dependencies or build the whole project if you want to test your change.</p><p><strong>BAZEL</strong>: Bazel is smarter. In the first step, Bazel constructs a dependency graph for each step.</p><p>Each step results in an SHA hash. If the SHA changes from the previous build the subsequent dependent actions will be triggered. This way, Bazel triggers only necessary steps and this makes the process faster.</p><p>In the below image say if Application5 has few changes in this case only the Application5 and its dependencies (highlighted in yellow) will be built by Bazel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*KJXZ0XBLH8mJzNYnZ1mcgg.jpeg" /></figure><p><strong>Question 2: Bazel avoids “Dependency Hell”</strong></p><p>With maven, we get a lot of transitive dependencies.</p><p>With Bazel we can make all the modules use the same dependency version. (You can use different versions of the same dependency in multiple modules, but Bazel strongly recommends Single Version Policy). This way once an artifact is updated in a single place, the whole repo will be referred to the updated version.</p><ol><li>Different modules use different version of same artifacts. (either because of same dependency or different version numbers in the respective pom)</li><li>In step 1 Bazel recommends to use Single Version Policy. This way dependency hell problem is avoided.</li></ol><p><strong>Question 3: How do I manage external dependencies using Bazel</strong></p><p>Bazel supports Maven. You can think of Bazel as a package that wraps Maven and other functionalities.</p><p>In case of Bazel all the internal dependencies are referred using the commit ID or SHA reference. External dependency can be referred using Maven. The maven repo will still be used by Bazel to download the external dependencies.</p><p><strong>Question 4: Configuration complexity</strong></p><p>BUILD can be considered as POM file. Bazel will automatically detect all the nested folders with BUILD file unlike Maven where we have to externally add the module to parent pom.</p><p>WORKSPACE file is like settings.xml file in Maven. It contains all the configuration details like maven dependencies, local references, Java image details etc…</p><p>All the maven dependency versions are defined in WORKSPACE file and BUILD file will just refer to the dependencies.</p><p><strong>Question 5: What about git submodules?</strong></p><p>Bazel is for Mono repo, whereas git submodules are used for poly repos. As mentioned earlier Bazel is a package with multiple functionalities.</p><p>You can use Bazel for poly repo too, in that case Bazel at high level acts as git submodule where the specific git version of the application will be referred directly.</p><p>Bazel also supports versioning with GIT SHA, which avoids direct dependency within internal code.</p><p>Overall, I find Bazel very much suitable for mono repos, and it addresses the pain of working on a big mono repo by taking smart decisions during build and package. This way it helps developers by saving more time during build process and helps organisation by utilising less resource.</p><p>Hope this overview of Maven vs Bazel is useful for people looking to switch!</p><p>Thanks for reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc32308dba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Short URL — System Design]]></title>
            <link>https://ruthreshwar.medium.com/short-url-system-design-cf1759d20ca?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf1759d20ca</guid>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 12:07:14 GMT</pubDate>
            <atom:updated>2021-06-06T12:07:14.023Z</atom:updated>
            <content:encoded><![CDATA[<h3>Short URL — System Design</h3><p>This is one of the most frequently asked or the basic system design question that we all have come over. There are lot of examples and design diagrams stacked over google search. Either there are too many details or it is too precise.</p><p>Let’s see the system design of Short Url in detail.</p><blockquote><strong>What is a Short URL?</strong></blockquote><p>Short URL is like alias of a long URL. Say if a long URL has to be shared via SMS or via phone call then it becomes tricky to share long URL’s. In these cases we can use some short URL as alias.</p><p>eg) <a href="https://www.example.com/home/nav/send/money?sender=Jonh&amp;receiver=Kim&amp;t=asdfdfadfafdadfadfdf">https://www.example.com/home/nav/send/money?sender=Jonh&amp;receiver=Kim&amp;t=asdfdfadfafdadfadfdf</a></p><p>The above URL when shortened gets mapped to</p><p><a href="https://www.tinyurl.com/dfsghij">https://www.shorturl.com/dfsghij</a></p><p>The value <strong>dfsghij</strong> is like hash code or unique code which will retrieve the long URL.</p><blockquote><strong>Requirements for Short URL</strong></blockquote><h4><strong>a. Functional Requirements</strong></h4><ol><li>Short URL application can be hosted as a REST service. It enables other developers and application to use service directly.</li><li>Short URL should have 2 operations</li></ol><blockquote>URL shortener — Given a long url this operation should return short url</blockquote><blockquote>URL expand — Given a short url this operation will return corresponding long url</blockquote><p>3. Short URL should give option to users to have their own custom url.</p><p>4. There should be some expiry time for the URL. Users should also be able to set the expiration date (not beyond a specific threshold).</p><p>5.<strong> Authentication</strong> — This can be kept optional. Since this is going to be open service any one should be able to hit our service with long URL.</p><p>6.<strong> RateLimiting</strong> — There are chances that hackers may spoof our system with too many requests (DDOS attack). There should be some mechanism to avoid this.</p><p>7. For duplicate long URL the short url service should return the same short URL for that user. If different user submits the same URL in that case both the short URL’s should be unique.</p><p><em>I guess we have listed down all the requirements to build the short URL. Now let’s move on to technical aspect of short URL.</em></p><p><strong>b. Non Functional Requirements</strong></p><p>8. <strong>Minimum latency/response time</strong> — Service should respond quickly (short &amp; expand).</p><p>9. <strong>High availability</strong> — If in case this service is down all the operations will start failing and will result in huge impact for the users.</p><p>10. <strong>Data eviction</strong> — Evict or archive old data</p><p>11. Short URL’s should not follow any pattern basically short URL should not be guessed by hackers.</p><blockquote><strong>Capacity Planning</strong></blockquote><p>Data modelling and system components design mainly depends on the usage of the service. So we will first figure out the usage details first before diving in deeper on data modelling.</p><p>Assume that we have 1 Million requests per day. It drills down to 30 Million requests per month.</p><p><strong>a. Data capacity planning</strong></p><p>Let’s say we store the data for 3 years.</p><p>Below is the calculation for how much data we will store in 3 years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMXgbi3xK_beNZ9gvQmGlQ.png" /><figcaption>Data Modelling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjMM3cwBVYZBowa-LOASTw.png" /><figcaption>Data calculation for 3 years</figcaption></figure><p>Apart from the above we will have user data too.</p><p><strong>b. Choosing Database</strong></p><p>As mentioned earlier the write and access should be very fast.</p><p>Also for this use case there will be lot of reads over writes.</p><p><strong>Option 1:</strong> Using RDBMS</p><p><strong>Advantages:</strong></p><ol><li>Provides ACID properties</li><li>Supports faster access based on indexing</li><li>High availability</li></ol><p><strong>Disadvantages:</strong></p><ol><li>RDBMS is not scalable for the larger number of data for this use case</li><li>Indexing based on hash (short url) makes read &amp; write slower for larger amount of data</li></ol><p>If we are choosing RDBMS then we have to DB partitioning and use extra layer for caching. We can consider using Redis distributed cache or LRU cache for this purpose.</p><p><strong>Option 2:</strong> Using NOSQL</p><p><strong>Advantages:</strong></p><ol><li>Provides eventual consistency</li><li>Easy to scale</li><li>High availability</li></ol><p>We can consider using any Key — Value data store like Dynamo DB or Oracle NOSQL DB</p><blockquote><strong>System Design</strong></blockquote><p><strong>a. High Level Design</strong></p><p>Our initial design of the system will look like below. Let’s see what can we tune here based on the functional and non functional requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbjawimX0f3_7_qAqxZ8Cw.png" /><figcaption>High Level Design</figcaption></figure><p><strong>b. Low Level Design</strong></p><p><strong>URL Short Service</strong></p><p>Let’s now bring back the requirements that we listed in first place.</p><p><strong>Requirement 1: </strong><em>Short URL should be hosted as a REST service</em></p><p>POST — <a href="https://api.tinyurl.com/v1/short">https://api.shorturl.com/v1/short</a></p><p>GET — https://api.shorturl.com/v1/expand/<a href="https://www.tinyurl.com/dfsghij">dfsghij</a></p><p><strong>Requirement 2:</strong> <em>Authentication</em></p><p>If authentication is needed we can use OAuth 2. But mostly short url will be open service without any authentication.</p><p><strong>Requirement 3:</strong> <em>RateLimiting</em></p><p>We need to prevent our service from DDOS attack. We need to introduce rate limiting based on Client IP address.</p><p>There are chances that the hacker may be from distributed system and invokes service from different IP address. In those cases observing traffic trend change could help in early prevention.</p><p>Once DDOS attack is identified add the IP address to a play book which will help in taking decision earlier when the attack repeats.</p><p><strong>Requirement 4:</strong> <em>User based URL generator</em></p><p>We cannot do search in database based on Long URL. So one way to find the duplicate long url is to create short url in such a way that it expands to long url with some hashing technique.</p><p>Let’s say we are using MD5 hash technique to calculate hash for the long url. MD5 hash generates 128-bit long output so out of 128 bit we will take 43 bit to generate a short URL of 10 characters.</p><p>MD5 can create a lot of collisions. For two or many different long URL inputs we may get the same unique id for short URL and that could cause data corruption. So we need to perform some checks to ensure that this unique id doesn’t exist in the database already.</p><p>In order to do this we can append the User ID to the end of the long URL before calculating hash. This will make sure every user has unique short url.</p><p><em>Let’s now look at Non Functional Requirements</em></p><p><strong>Requirement 5:</strong> <em>Minimum Latency/Response time</em></p><p>To achieve this we can introduce a distributed cache which will have faster access time.</p><p>We should decide on how much data we need to store in cache and cache eviction policy and choose cache storage accordingly.</p><p><strong>Requirement 6:</strong> <em>High availability</em></p><p>Below are the failure points</p><ol><li>Application server</li><li>Database</li></ol><p>We can add multiple application server against a load balancer and monitor the heart beat of the application. If server is down we should replace the server with a new server.</p><p>For database we can introduce a back up/replica DB. There are multiple replication technique which can be chose based on the use case.</p><p>After considering all the requirements now our system looks like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nmg2xW3K0dUmiwHnpEP3Q.png" /><figcaption>Final System Design</figcaption></figure><p>Below are some questions that may come out of the design</p><ol><li><em>What happens when there are concurrent requests </em>→ This is handled using hashing. During insert we should make sure we don’t have duplicate keys.</li><li><em>How to get metrics on location, users etc..</em> → We should get this clarified at initial requirement phase. Based on the input we can add columns to the User table.</li><li><em>What happens if the connection to DB is down</em> → Our application should fall back to the Replica DB in case of original DB failure</li><li><em>How writes are handled</em> → Writes to DB will happen synchronously. For replicas the writes may happen async based on the quorum configuration.</li></ol><p>Thanks for reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf1759d20ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactor Series: How to make API call with Spring Reactor]]></title>
            <link>https://ruthreshwar.medium.com/reactor-series-how-to-make-api-call-with-spring-reactor-c469459ae80d?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/c469459ae80d</guid>
            <category><![CDATA[spring-reactor]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java-spring-reactor]]></category>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[non-blocking-io]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 04:41:11 GMT</pubDate>
            <atom:updated>2020-12-10T04:41:11.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*jm25R2_0Xl0u3hlTwO-XqQ.png" /><figcaption>Spring Reactor</figcaption></figure><p>To call an API from spring reactor you need to know about <strong>WebClient</strong></p><p>Before Spring 5 we consume any REST service by using either one of the below</p><p>a. URL (provided by java.net package)</p><p>b. RestTemplate (provided by Spring framework)</p><p>c. HttpClient’s (provided by JaxRS or Apache etc…)</p><p>Most of the clients that facilitate to consume API’s are blocking in nature.</p><p>e.g) If you make a request to get details of the users from a service your execution thread will be held till the response returns back from the server. Only after receiving response the next instructions will be processed.</p><p>Blocking threads are becoming a bottle neck in high traffic systems. Every time a client requests for some information from API a dedicated thread will be waiting to hear response from the service. The thread will be in idle state till response is received from the API. If system is busy the idle threads cannot be reused. To avoid this bottle neck we have libraries that can help us to make an Async Call and return a Future (Future was introduced as part of java.concurrent package in Java 5).</p><p>The overhead with the async client (I/O calls doesn’t hold the main thread) libraries are</p><ol><li>Thread pool has to be managed by the developers</li><li>A dedicated thread will be involved for processing after the async task is complete</li><li>No support for high level functions to process the response (like map, flatMap etc…). High level functions make the code more readable and as a result we can deliver quality code without bugs.</li><li>No support for handling errors.</li></ol><p><strong>Sample Client Code:</strong></p><p><strong>RestTemplate:</strong></p><pre>RestTemplate restTemplate = new RestTemplate();</pre><pre>String resource = <strong>&quot;</strong>http://localhost:8080/employees<strong>&quot;</strong>;</pre><pre>ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(resource, String.class);</pre><p><strong>Async RestTemplate:</strong></p><pre>HttpClient client = HttpClient.newBuilder().version(Version.HTTP_2).build();</pre><pre>HttpRequest request = HttpRequest.newBuilder(URI.create(“http://localhost:8080/employees”))</pre><pre>CompletableFuture&lt;HttpResponse&lt;String&gt;&gt; response = client.sendAsync(request,HttpResponse.BodyHandlers.ofString());</pre><p><strong>WebClient</strong>:</p><pre>WebClient client = WebClient.<em>create</em>(<strong>&quot;</strong>http://localhost:8080/<strong>&quot;</strong>);<br><br>Mono&lt;ClientResponse&gt; result = client.get()<br>        .uri(&quot;employees&quot;)<br>        .accept(MediaType.<em>TEXT_PLAIN</em>)<br>        .exchange();</pre><p>In AsyncHttpClient the actual call will be made when client.sendAsync is invoked. This is not the case for WebClient client.get() will not invoke the actual call.</p><p>Mono/Flux is a promise (Future) where it says there will be a result available. The actual call is deferred. Unless one subscribes or block the mono the action will not be invoked.</p><p>For WebClient to work we should add below lines</p><p>result.subscribe(e -&gt; System.out.println(e)) or result.bodyToMono(String.class).block()</p><p>Let’s now try to solve the below problem</p><p>A company wants to organize an event to celebrate gender diversity in their company. Now the company wants to send out invites for all the female employees in the company.</p><p>The company has a paginated api which returns all the users with details like id, gender and DOB.</p><p>There is another API which will return the details of user like email id, address etc…</p><p>Now our task is to make use of those 2 API’s and print the email id’s of all the female employees in that company.</p><p>Let’s try to do this task with both AsyncHttpClient and then we will try with WebClient</p><p><strong>AsyncRestTemplate</strong></p><pre>AsyncRestTemplate restTemplate = new<strong> </strong>AsyncRestTemplate();<br>String baseUrl = &quot;https://gorest.co.in/public-api/users?page=&quot;;<br><br>List&lt;Future&lt;ResponseEntity&lt;Example&gt;&gt;&gt; collect = IntStream.<em>range</em>(1, 5)<br>        .mapToObj(e -&gt; {<br>            Future&lt;ResponseEntity&lt;Example&gt;&gt; futureEntity = restTemplate.getForEntity(baseUrl + e, Example.class);<br>            return<strong> </strong>futureEntity;<br>        })<br>        .collect(Collectors.<em>toList</em>());<br><br>collect.stream()<br>        .parallel()<br>        .forEach(future -&gt; <em>logger</em>.info(<em>uncheckedSupplier</em>(future::get).get().getBody().toString()));</pre><p>wait wait!!! Did this code solve the purpose? NO</p><p>In this code we have just called the API 5 times and fetching the body. Next we have to add filter on the body and then again make API calls like above and then trigger notification. Uffff….</p><p>Okay now let’s give a try with WebClient</p><pre>Flux.<em>range</em>(1, 5)<br>        .flatMap(i -&gt; client.get()<br>                .uri(&quot;public-api/users?page={id}&quot;, i)<br>                .retrieve()<br>                .bodyToMono(Example.<strong>class</strong>))<br>        .flatMapIterable(e -&gt; e.getData()<br>                .stream()<br>                .filter(in -&gt; in.getGender().equalsIgnoreCase(<strong>&quot;</strong>female<strong>&quot;</strong>))<br>                .map(i -&gt; i.getId())<br>                .collect(Collectors.<em>toList</em>()))<br>        .delayElements(Duration.<em>ofMillis</em>(1000))<br>        .flatMap(i -&gt; client.get()<br>                .uri(&quot;public-api/users/&quot;+ i)\<br>                .retrieve()<br>                .bodyToMono(User.class))<br>        .doOnNext(e -&gt; <strong><em>logger</em></strong>.info(e.getData().getEmail()))<br>        .blockLast();</pre><p>Its Done!!! Continue reading to understand what code is doing</p><p>We have an API that returns list of Users. The API is paginated and we get 20 results per page.</p><p>The ask is to call the API (here I have called 5 pages). Below code does this work.</p><p>** Please look at the code comments for more clarity</p><pre>Flux.<em>range</em>(1, 5) <strong>// Integer range 1 to 5</strong><br>        .flatMap(i -&gt; client.get() <strong>// HTTP method converted to method</strong><br>        .uri(<strong>&quot;</strong>public-api/users?page={id}<strong>&quot;</strong>, i)<br>        .retrieve() <strong>// gets the response body</strong><br>        .bodyToMono(Example.class)) <strong>// Single result will be returned here so bodyToMono is used. </strong></pre><p>Our next task is to filter the list and get all female users.</p><pre>.flatMapIterable(e -&gt; e.getData() <strong>// flatMapIterable is used because the result of this is going to be a list. flatMapIterable will flatten multiple lists.</strong><br>                .stream()<br>                .filter(in -&gt; <br>                        in.getGender().equalsIgnoreCase(<strong>&quot;</strong>female<strong>&quot;</strong>))<br>                .map(i -&gt; i.getId())<br>                .collect(Collectors.<em>toList</em>())) </pre><p>Next task is to get email id of those selected users</p><pre>.delayElements(Duration.<em>ofMillis</em>(1000)) <strong>// Added delay to avoid spike in service</strong><br>        .flatMap(i -&gt; client.get()<br>                .uri(<strong>&quot;</strong>public-api/users/<strong>&quot;</strong>+ i)<br>                .accept(MediaType.<em>TEXT_PLAIN</em>)<br>                .retrieve()<br>                .bodyToMono(User.class))</pre><p>Next is to log those email id’s</p><pre>.doOnNext(e -&gt; <em>logger</em>.info(e.getData().getEmail())) <strong>// For each ID onNext will be called</strong><br>.blockLast(); <strong>// Till last item is emitted the Flux will be blocked</strong></pre><p><strong>Key points to remember:</strong></p><ol><li>flatMap is different from Java and Reactor. In reactor flatMap will auto subscribe and return the Flux. So it is mandatory that the return value should be of type Mono or Flux</li><li>flatMap uses different thread for any async processing</li><li>The number of threads in reactor is limited to 4 per core. Threads will be reused</li><li>In our sample if first flatMap use 4 threads then the 4 will reuse those 4 threads but order is not guaranteed</li><li>Unless one subscribes/blocks the stream action will not be performed. The stream is basically a blue print without subscribe or block action.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c469459ae80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N Queens Problem For Beginners]]></title>
            <link>https://ruthreshwar.medium.com/n-queens-problem-for-beginners-916543fb2cc0?source=rss-248fa955a348------2</link>
            <guid isPermaLink="false">https://medium.com/p/916543fb2cc0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[queens-problem]]></category>
            <category><![CDATA[backtracking]]></category>
            <category><![CDATA[beginner-simple]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ruthreshwar Gajendiran]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 14:07:24 GMT</pubDate>
            <atom:updated>2020-08-12T05:59:54.522Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are NOT aware of backtracking and basics of recursion then this write up is for YOU!!!</p><p>Problem Statement:</p><p>We have a chess board of size 8x8 matrix.</p><p>We have to place 8 queens in the board such that no queens attack each other.</p><p>(Queen can move horizontally, vertically and diagonally in any direction)</p><figure><img alt="Queen moves in a chess board" src="https://cdn-images-1.medium.com/max/480/1*C2iy0rs8Q6VWCtT1JglDWg.gif" /><figcaption>Queen placements in chess board</figcaption></figure><p>Algorithm:</p><p>We can approach the solution by placing Queen one by one in the best possible location.</p><p>For simplicity let us discuss about the placing queens in 4x4 matrix.</p><p>There are only 3 scenarios possible</p><p>Scenario 1: We are starting to solve the problem and we are free to place the queen anywhere in board. We will start with top-left position.</p><p>a — We see that the position (0,0) is safe as there are no other queens in the board.</p><p>b — Place the queen in (0,0) index</p><figure><img alt="Scenario 1" src="https://cdn-images-1.medium.com/max/712/1*Oc_ZTgvqyxM8PfzmUfFssQ.png" /><figcaption>Scenario 1</figcaption></figure><p>Scenario 2: Placing the queen in next column (ROW, COLUMN) (Instead of column you can choose to iterate over row also.)</p><figure><img alt="Scenario 2" src="https://cdn-images-1.medium.com/max/702/1*1oBMm6wS4mn96Tou2jfQMQ.png" /><figcaption>Scenario 2</figcaption></figure><p>a — We have to check if the position is safe. If the position is not safe keep incrementing the row value to traverse vertically and check for safe position</p><p>b — Place the queen in its first safe position. In our use case the first safe position is (1,2). Refer to pic below</p><p>c — Increment the column after placing the queen in safe position and follow Scenario 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*qlWVwNrK-dJGd6BJeMbeUA.png" /></figure><p>Scenario 3: If there are no safe positions for the queen</p><p>a — Subtract the column value by 1 and follow Scenario 2</p><p>b — While following Scenario 2 there will already be a queen placed in that row. We now need to place the queen in next safe position.</p><p>(The above mentioned point is called backtracking where we are maintaining the previous result and trying to correct previous result to check if we can attain our final outcome)</p><p>Observations before starting to code:</p><p>If you observe the scenarios you can guess on what way we can approach to write code for this. Below are all the points which can be derived from the algorithm</p><ol><li>In Scenario 2 it is mentioned that “keep incrementing the row value to traverse horizontally and check for safe position” → This implies that we have to maintain a loop to increment ROW values.</li><li>In Scenario 2 it is also mentioned that “Increment the column after placing the queen in safe position and follow Scenario 2.” → This implies that we have need one more loop to increment COLUMN values.</li><li>It is also mentioned that “trying to correct previous result” → This implies that we need to store the previous result value in some form so that we can go back and revisit the decision.</li></ol><p>Coding Approach:</p><p>Let us first break the problem in to smaller unit of work.</p><ol><li>First piece of logic is to write a method which will have logic to check if the given position is safe or not. (Check if the queen is with in borders and no queen can attack the new queen)</li><li>Second piece of logic is to write a method which takes care of maintaining the loop to traverse the matrix horizontally (You can even choose to traverse vertically).</li><li>The last piece is to have logic to execute in recursion with backtracking.</li></ol><p>Let Us Start Coding:</p><p>JAVA:</p><ol><li>First piece of logic to validate if position is safe</li></ol><pre>public boolean isSafePosition(int[][] matrix, int row, int column) {<br>       <br>       <strong><em>// Check for safety in that column<br>       // We can skip this because we will not have any values in the column initially.</em></strong></pre><pre>       for(int i=0 ; i &lt; column; i++) {<br>              if(matrix[row][i] == &#39;Q&#39;) //Column traversal<br>                        return false;<br>       }</pre><pre>       <strong><em>// Check for safety in that row</em></strong></pre><pre>       for(int i=row ; i &gt; 0; i--) {<br>              if(matrix[i][row] == &#39;Q&#39;) //Row traversal<br>                        return false;<br>       }</pre><pre>       <strong><em>// Check for safety in left to top diagonal<br>       // We are checking only left diagonal because we haven&#39;t placed any queen on the right side yet.</em></strong></pre><pre>for(int i=row, j=column ; i &gt; 0 &amp; j &gt; 0; i--, j--) {<br>              if(matrix[i][j] == &#39;Q&#39;) //Left top diagonal traversal<br>                        return false;<br>       }</pre><pre><strong><em>       // Check for safety in left to down diagonal<br>       // We are checking only left diagonal because we haven&#39;t placed any queen on the right side yet.</em></strong></pre><pre>       for(int i=row, j=column ; i &gt; 0 &amp; j &lt; N; i--, j++) {<br>              if(matrix[i][j] == &#39;Q&#39;) //Left down diagonal traversal<br>                        return false;<br>       }<br>       <br>       return true;</pre><pre>}</pre><p>2. Second piece of logic to traverse matrix (Chess board)</p><pre>public boolean NQueen(int[][] matrix, int row) {<br>       if(row &gt;= N) return true;<br>       for(int i=0; i&lt; N; i++) {<br>             if(isSafe(matrix, row, i) {<br>                    matrix[row][col] = &#39;Q&#39;;<br>                    if(NQueen(matrix, row+1, i)) return true;<br>                    matrix[row][col] = &#39;O&#39;;<br>            }<br>       return false;<br>}</pre><p>In the above use case back tracking happens when ‘FALSE’ is returned. When FALSE is returned we reset the matrix value from Q to O and then look for safe position.</p><p>3. Execute the program</p><pre>public static void main(String args[]) {<br>       // Declare the matrix size<br>       int[][] matrix = new int[4][4];<br>       NQueen(matrix, 0);<br>       // Iterate matrix and print the solution<br>}</pre><p>Thanks for reading!!! Please leave your comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916543fb2cc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>