<?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 Karthik on Medium]]></title>
        <description><![CDATA[Stories by Karthik on Medium]]></description>
        <link>https://medium.com/@karthikeswar_?source=rss-834db34ecc77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zmLeBulvOhHFj9VLkr764w@2x.jpeg</url>
            <title>Stories by Karthik on Medium</title>
            <link>https://medium.com/@karthikeswar_?source=rss-834db34ecc77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:22:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthikeswar_/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[Future vs CompletableFuture: The Only Guide You Need]]></title>
            <link>https://medium.com/@karthikeswar_/future-vs-completablefuture-the-only-guide-you-need-a8591273d011?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8591273d011</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[completablefuture]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 10:05:44 GMT</pubDate>
            <atom:updated>2026-02-18T06:04:21.450Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 5-minute guide to understanding asynchronous programming in Java</em></p><h3>The Problem: Waiting is Wasteful</h3><p>Imagine you’re building a user profile API that needs to fetch:</p><ul><li>User data from database (1 second)</li><li>Order history from another service (1 second)</li><li>Loyalty points from a third service (1 second)</li></ul><p><strong>The old way (blocking):</strong></p><pre>String user = fetchUser();      // Wait 1 sec<br>String orders = fetchOrders();  // Wait 1 sec<br>String points = fetchPoints();  // Wait 1 sec<br>// Total: 3 seconds 😢</pre><p><strong>The async way:</strong></p><pre>// All three run in parallel<br>CompletableFuture&lt;String&gt; userCF = CompletableFuture.supplyAsync(() -&gt; fetchUser());<br>CompletableFuture&lt;String&gt; ordersCF = CompletableFuture.supplyAsync(() -&gt; fetchOrders());<br>CompletableFuture&lt;String&gt; pointsCF = CompletableFuture.supplyAsync(() -&gt; fetchPoints());<br>// Total: 1 second 🚀</pre><p>This is where Future and CompletableFuture come in.</p><h3>What is Asynchronous Execution?</h3><p><strong>Async = Background thread + Main thread continues</strong></p><pre>System.out.println(&quot;Line 1: Start&quot;);<br>CompletableFuture.supplyAsync(() -&gt; {<br>    sleep(3000); // Runs in background<br>    return &quot;Done&quot;;<br>});<br>System.out.println(&quot;Line 2: This prints immediately!&quot;);<br>System.out.println(&quot;Line 3: Main thread continues...&quot;);</pre><p><strong>Output:</strong></p><pre>Line 1: Start<br>Line 2: This prints immediately!  ← Main thread doesn&#39;t wait<br>Line 3: Main thread continues...</pre><p>The task runs in a <strong>separate thread</strong> while your main code keeps executing.</p><h3>Future: The Simple Wrapper (Java 5)</h3><p><strong>Future</strong> is a simple promise: “I’ll give you a result eventually.”</p><pre>ExecutorService executor = Executors.newFixedThreadPool(5);<br>Future&lt;String&gt; future = executor.submit(() -&gt; {<br>    Thread.sleep(1000);<br>    return &quot;Result&quot;;<br>});<br>System.out.println(&quot;Task running...&quot;);<br>String result = future.get(); // BLOCKS here until ready<br>System.out.println(result);</pre><p><strong>The problem?</strong> You <strong>must block</strong> with .get() to retrieve the result. No callbacks, no chaining, no composition.</p><h3>CompletableFuture: The Smart Wrapper (Java 8)</h3><p><strong>CompletableFuture</strong> is Future’s smarter sibling with superpowers.</p><h3>1. Non-blocking Callbacks</h3><pre>CompletableFuture.supplyAsync(() -&gt; &quot;Result&quot;)<br>    .thenApply(result -&gt; result.toUpperCase())<br>    .thenAccept(result -&gt; System.out.println(result));<br>// Main thread continues immediately!</pre><h3>2. Combining Multiple Tasks</h3><pre>CompletableFuture&lt;String&gt; user = <br>      CompletableFuture.supplyAsync(() -&gt; fetchUser());<br>CompletableFuture&lt;String&gt; orders = <br>      CompletableFuture.supplyAsync(() -&gt; fetchOrders());<br>String combined = user.thenCombine(orders, (u, o) -&gt; u + &quot; + &quot; + o).get();</pre><h3>3. Error Handling</h3><pre>CompletableFuture.supplyAsync(() -&gt; {<br>    throw new RuntimeException(&quot;Failed!&quot;);<br>})<br>.exceptionally(ex -&gt; &quot;Fallback data&quot;) // Graceful recovery<br>.thenAccept(System.out::println);</pre><h3>4. Timeouts</h3><pre>CompletableFuture.supplyAsync(() -&gt; slowService())<br>    .orTimeout(2, TimeUnit.SECONDS)<br>    .exceptionally(ex -&gt; &quot;Cached data&quot;);</pre><h3>Side-by-Side Comparison</h3><pre>Feature             Future                        CompletableFuture<br>Callbacks           ❌ None                        ✅ thenApply, thenAccept <br>Chaining            ❌ Manual                      ✅ Fluent API <br>Combining           ❌ Block each separately       ✅ thenCombine, allOf <br>Error handling      ❌ Try-catch only              ✅ exceptionally, handle <br>Timeouts            ❌ None                        ✅ orTimeout <br>Manual completion   ❌ No                          ✅ complete()</pre><p><strong>Real-World Example: API Aggregation</strong></p><p><strong>Problem:</strong> Fetch from 3 services, use cached data if any fail.</p><h3>With Future (The Hard Way)</h3><pre>Future&lt;String&gt; service1 = executor.submit(() -&gt; callService1());<br>Future&lt;String&gt; service2 = executor.submit(() -&gt; callService2());<br>Future&lt;String&gt; service3 = executor.submit(() -&gt; callService3());</pre><pre>String result1;<br>try {<br>    result1 = service1.get(1, TimeUnit.SECONDS);<br>} catch (Exception e) {<br>    result1 = cache.get(&quot;service1&quot;);<br>}</pre><pre>String result2;<br>try {<br>    result2 = service2.get(1, TimeUnit.SECONDS);<br>} catch (Exception e) {<br>    result2 = cache.get(&quot;service2&quot;);<br>}</pre><pre>// Repeat for service3... 😫</pre><h3>With CompletableFuture (The Elegant Way)</h3><pre>CompletableFuture&lt;String&gt; cf1 = CompletableFuture<br>    .supplyAsync(() -&gt; callService1())<br>    .orTimeout(1, TimeUnit.SECONDS)<br>    .exceptionally(ex -&gt; cache.get(&quot;service1&quot;));<br>CompletableFuture&lt;String&gt; cf2 = CompletableFuture<br>    .supplyAsync(() -&gt; callService2())<br>    .orTimeout(1, TimeUnit.SECONDS)<br>    .exceptionally(ex -&gt; cache.get(&quot;service2&quot;));<br>CompletableFuture&lt;String&gt; cf3 = CompletableFuture<br>    .supplyAsync(() -&gt; callService3())<br>    .orTimeout(1, TimeUnit.SECONDS)<br>    .exceptionally(ex -&gt; cache.get(&quot;service3&quot;));<br>// Combine all three<br>String result = cf1<br>    .thenCombine(cf2, (r1, r2) -&gt; r1 + r2)<br>    .thenCombine(cf3, (combined, r3) -&gt; combined + r3)<br>    .get();</pre><h3>When Do I Wait for the Result?</h3><p><strong>Q:</strong> “If tasks run in background, how do I ensure the result is ready before using it?”</p><p><strong>3 Solutions:</strong></p><h3>1. Block and Wait</h3><pre>CompletableFuture&lt;String&gt; cf = CompletableFuture.supplyAsync(() -&gt; &quot;Data&quot;);<br>String result = cf.get(); // WAIT HERE<br>processData(result); // Now safe to use</pre><h3>2. Use Callbacks (Non-blocking)</h3><pre>CompletableFuture.supplyAsync(() -&gt; &quot;Data&quot;)<br>    .thenAccept(result -&gt; {<br>        // This runs ONLY AFTER async task completes<br>        processData(result);<br>    });</pre><h3>3. Wait for All Tasks</h3><pre>CompletableFuture&lt;String&gt; task1 = CompletableFuture.supplyAsync(() -&gt; &quot;A&quot;);<br>CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(() -&gt; &quot;B&quot;);<br>CompletableFuture.allOf(task1, task2).get(); // Wait for both<br>// Now both are ready</pre><h3>Key Takeaways</h3><ol><li><strong>Async = background thread</strong>, main thread continues</li><li><strong>Future = simple wrapper</strong>, must block to get result</li><li><strong>CompletableFuture = smart wrapper</strong>, callbacks + chaining + composition</li><li><strong>Use </strong><strong>.get() when you need to wait</strong> for the result</li><li><strong>Use callbacks (</strong><strong>.thenApply())</strong> to avoid blocking</li><li><strong>Always use CompletableFuture</strong> for new code — Future is obsolete</li></ol><h3>Production Tips</h3><h3>✅ DO:</h3><ul><li>Use custom thread pools for I/O operations</li></ul><pre>ExecutorService ioPool = Executors.newFixedThreadPool(50);<br>CompletableFuture.supplyAsync(() -&gt; dbCall(), ioPool);</pre><ul><li>Handle errors gracefully</li></ul><pre>.exceptionally(ex -&gt; fallbackValue)</pre><ul><li>Add timeouts</li></ul><pre>.orTimeout(2, TimeUnit.SECONDS)</pre><h3>❌ DON’T:</h3><ul><li>Use ForkJoinPool.commonPool() for blocking I/O</li><li>Forget to handle exceptions</li><li>Chain too many operations without error handling</li></ul><p><strong>Q:</strong> “How would you fetch data from 5 microservices in parallel, with 1-second timeout per service, and fallback to cache if any fail?”</p><p><strong>Answer:</strong></p><pre>List&lt;CompletableFuture&lt;String&gt;&gt; futures = services.stream()<br>    .map(service -&gt; CompletableFuture<br>        .supplyAsync(() -&gt; service.call())<br>        .orTimeout(1, TimeUnit.SECONDS)<br>        .exceptionally(ex -&gt; cache.get(service.name())))<br>    .collect(Collectors.toList());<br>CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();<br>List&lt;String&gt; results = futures.stream()<br>    .map(CompletableFuture::join)<br>    .collect(Collectors.toList());</pre><h3>The Bottom Line</h3><p><strong>Future</strong> is like waiting at a counter for your food.<br> <strong>CompletableFuture</strong> is like getting a buzzer and sitting down while it’s prepared.</p><p>For modern Java applications, <strong>always choose CompletableFuture</strong>. It’s not just faster — it’s more resilient, composable, and maintainable.</p><p><a href="https://gist.github.com/Karthikeswar-a/d8c93bc943a105b0685e96b2977ffc42">GitHub: Simple Java main class that features Future and CompletableFuture usage.</a></p><p><strong>Note: Generated from a conversation with Claude Sonet 4.5 😌</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8591273d011" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 -Mastering the Sliding Window Dynamic Range Technique]]></title>
            <link>https://medium.com/@karthikeswar_/day-4-811768b82fe2?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/811768b82fe2</guid>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 16:00:54 GMT</pubDate>
            <atom:updated>2026-02-08T11:20:54.800Z</atom:updated>
            <content:encoded><![CDATA[<p>The sliding window technique is one of the most powerful patterns in algorithm design, transforming seemingly complex O(n²) problems into elegant O(n) solutions. In this article, we’ll explore two classic problems that demonstrate the versatility of this approach, from basic implementation to optimized solutions.</p><h4>The Sliding Window Mindset</h4><p>Before diving into code, let’s understand the core concept. The sliding window technique maintains a dynamic range (window) within an array or string, expanding or contracting based on specific conditions. Think of it as looking through a adjustable window that slides across your data, always keeping track of the optimal view.</p><p><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/description/"><strong>Longest Substring Without Repeating Characters</strong></a></p><p><strong>The Challenge:</strong> Given a string, find the length of the longest substring without repeating characters.</p><p>For example, in the string “abcabcbb”, the answer is 3 (“abc”), while “bbbbb” returns 1 (“b”).</p><h4>Approach 1: HashMap with Count Tracking</h4><p>The first solution uses a frequency map to track character occurrences within our window:</p><p>So the steps to approach this would be:</p><ol><li>Read the string one character at a time, from left to right</li><li>Use HashMap to record how many times each letter appears in your current section.</li><li>If increment makes(count &gt; 1), you have a duplicate!</li><li>Start a loop moving left pointer and decrementing each character count until the duplicate is gone (count returns to 1)</li><li>Once while loop complete save the result with max( i.e Max(result, right-left+1))</li></ol><pre>public int lengthOfLongestSubstring(String s) {<br>        int res = 0;<br>        Map&lt;Character, Integer&gt; a = new HashMap&lt;&gt;();<br>        int left = 0;<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            a.put(s.charAt(i), a.getOrDefault(s.charAt(i), 0) + 1);<br><br>            while (a.get(s.charAt(i)) &gt; 1) {<br>                a.put(s.charAt(left), a.get(s.charAt(left)) - 1);<br>                left++;<br>            }<br>            res = res &gt; i - left + 1 ? res : i - left + 1;<br><br>        }<br>        return res;<br>}</pre><p><strong>Time Complexity:</strong> O(n) — each character is visited at most twice <strong>Space Complexity:</strong> O(min(n, m)) where m is the character set size</p><p>There is even better approach where we can eliminate the while loop in it.</p><p>Instead of looping in when there is a duplicate<br>We will just replace the left to the current index in loop</p><pre>public int lengthOfLongestSubstring(String s) {<br>        int res = 0;<br>        Map&lt;Character, Integer&gt; a = new HashMap&lt;&gt;();<br>        int left = 0;<br>        for (int i = 0; i &lt; s.length(); i++) {<br>            if(a.containsKey(s.charAt(i))){<br>                left = Math.max(left, a.get(s.charAt(i))+1);<br>            }<br>            a.put(s.charAt(i), i);<br>            res = res &gt; i - left + 1 ? res : i - left + 1;<br><br>        }<br>        return res;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ohtam-_u8YIIWFuCjS2KbQ.png" /><figcaption>AI Generated mistakes can be there</figcaption></figure><p><a href="https://leetcode.com/problems/minimum-window-substring/"><strong>Minimum Window Substring</strong></a></p><p><strong>The Challenge:</strong> Given strings s and t, find the minimum window in s that contains all characters of t (including duplicates).</p><p>For example:</p><ul><li>s = “ADOBECODEBANC”, t = “ABC” → “BANC”</li><li>s = “a”, t = “a” → “a”</li></ul><p>This problem takes the sliding window technique to the next level with variable-size windows.</p><p><strong>Thought process:</strong></p><ol><li>We will create two arrays a[128], b[128]. In <strong><em>a</em></strong> we store string <strong><em>t</em></strong> chars occurrence/ count and <strong><em>b </em></strong>is used for window.</li><li>First loop with size of <strong><em>t</em></strong> and add all occurrrence of <strong><em>t</em></strong> and <strong><em>s</em></strong> chars in <strong><em>a</em></strong> and <strong><em>b</em></strong> respectively</li><li>Now start 2nd loop that starts with <strong><em>size(t)</em></strong> to <strong><em>size(s)</em></strong></li><li>Here we add the element to <strong><em>b</em></strong> and check the window to see if it has all the chars of <strong><em>a</em></strong>.</li><li>If present we save the result and length to variable only if <strong><em>previous length</em></strong> <strong><em>&gt;</em></strong> <strong><em>current window length.</em></strong></li><li>Then we shrink the array by incrementing the <strong><em>left</em></strong> pointer until the frequency of <strong><em>a</em></strong> and <strong><em>b</em></strong> is broken.</li><li>End the loop and return result.</li></ol><pre>class Solution {<br><br>    public static String minWindow(String s, String t) {<br><br>        String result = &quot;&quot;;<br><br>        if (t.length() &gt; s.length()) {<br>            return result;<br>        }<br>        int[] a = new int[128];<br>        int[] b = new int[128];<br>        int left = 0;<br>        int length = Integer.MAX_VALUE;<br><br>        for (int i = 0; i &lt; t.length(); i++) {<br>            a[t.charAt(i)]++;<br>            b[s.charAt(i)]++;<br>        }<br><br>        if (isArrayEquals(a, b)) {<br>            return s.substring(0, t.length());<br>        }<br><br>        for (int i = t.length(); i &lt; s.length(); i++) {<br>            b[s.charAt(i)]++;<br>            while(isArrayEquals(a, b) &amp;&amp; left&lt;=i){<br>                if(length &gt; i-left+1){<br>                    length = i-left+1;<br>                    result = s.substring(left,i+1);<br>                }<br>                b[s.charAt(left)]--;<br>                left++;<br>            }<br><br>        }<br><br>        return result;<br><br>    }<br><br>    private static boolean isArrayEquals(int[] a1, int[] a2) {<br>        for (int i = 0; i &lt; a1.length; i++) {<br>            if (a1[i] != 0 &amp;&amp; a1[i] &gt; a2[i]) {<br>                return false;<br>            }<br>        }<br>        return true;<br>    }<br>}</pre><p>The main logic is using while loop inside the for loop to shrink the window until the match is found. That’s the way to go for Variable Sliding window technique.</p><p>But there is a scope of improvement here. The culprit is the way we are checking both arrays. It loops through 128 times to check frequency.</p><p>This can be taken down by adding two more variables in our logic. Let’s see the updated Algo</p><ol><li>Initialize variables<br><strong><em>int formed = 0, uniqueCharsRequired = 0, left = 0, <br>minStart = 0, length = Integer.MAX_VALUE;<br>int[] required = new int[128]; int[] window = new int[128];</em></strong></li><li>First loop only check the string t occurrences in required array</li><li>Second loop start with index <strong><em>int right = 0; right&lt; s.length(); right++</em></strong></li><li>Lets say <strong><em>c = s.charAt(right) </em></strong>then increment<strong><em> window[c]++</em></strong></li><li>Now if <strong><em>required[c] == window[c]</em></strong> we increment formed</li><li>Then check if <strong><em>formed == uniqueCharsRequired</em></strong></li><li>If so, and <strong><em>right-left &lt; length</em></strong> record <strong><em>minStart = left, length = right-left+1</em></strong><br>This way we will know the min length and index start point for substring</li><li>Then follow the normal shrinking process if criteria meets by left++ and decrement formed- appropriately.</li><li>Once loop is completed return <strong><em>s.subString(minStart, minStart+length+1)</em></strong></li></ol><pre>public static String minWindow(String s, String t) {<br>        if (t.length() &gt; s.length()) {<br>            return &quot;&quot;;<br>        }<br>        int formed = 0, uniqueCharsRequired = 0, left = 0, minStart = 0,length = Integer.MAX_VALUE;<br>        int[] required = new int[128];<br>        int[] window = new int[128];<br><br>        for(char c : t.toCharArray()){<br>            if(required[c]==0){<br>                uniqueCharsRequired++;<br>            }<br>            required[c]++;<br>        }<br><br>        for(int right = 0; right&lt; s.length(); right++){<br><br>            char c = s.charAt(right);<br>            window[c]++;<br><br>            if(window[c] == required[c]){<br>                formed++;<br>            }<br>            while(formed == uniqueCharsRequired &amp;&amp; left&lt;=right){<br>                if(length &gt; right-left+1){<br>                    length = right-left+1;<br>                    minStart = left;<br>                }<br><br>                char leftChar = s.charAt(left);<br>                window[leftChar]--;<br><br>                if (required[leftChar] &gt; 0 &amp;&amp; window[leftChar] &lt; required[leftChar]) {<br>                    formed--;<br>                }<br><br>                left++;<br>            }<br><br>        }<br><br>        return length == Integer.MAX_VALUE ? &quot;&quot; : s.substring(minStart, minStart + length);<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNqaV-q4-3lvzKGBVOSULg.png" /><figcaption>AI Generated mistakes can be there</figcaption></figure><h3>The Variable Sliding Window Pattern</h3><p>Both optimized solutions demonstrate the core pattern for variable sliding windows:</p><pre>1. Expand window (move right pointer)<br>2. While window is valid:<br>   a. Record/update result<br>   b. Shrink window (move left pointer)<br>   c. Check if still valid<br>3. Repeat until right pointer reaches the end</pre><p>The nested while loop is the hallmark of variable sliding windows. Unlike fixed-size windows that simply slide, variable windows actively expand and contract to find the optimal range.</p><h3>Conclusion</h3><p>The sliding window technique transforms brute-force nested loops into single-pass algorithms. The key insights are:</p><ol><li><strong>Use HashMaps/Arrays</strong> to track window state efficiently</li><li><strong>Optimize validation</strong> by maintaining counters instead of scanning entire data structures</li><li><strong>Think in two phases</strong>: expand to meet conditions, then contract to optimize</li><li><strong>Choose the right pointer movement</strong>: sometimes you can jump, sometimes you must increment</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=811768b82fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3: Mastering Sliding Window Technique]]></title>
            <link>https://medium.com/@karthikeswar_/day-3-7c4f7e355f5e?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c4f7e355f5e</guid>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 07:43:54 GMT</pubDate>
            <atom:updated>2026-02-08T11:21:58.854Z</atom:updated>
            <content:encoded><![CDATA[<p>The sliding window technique is a powerful algorithmic pattern that transforms problems with O(n²) complexity into elegant O(n) solutions. Today, we’ll explore two classic problems that demonstrate the versatility of this approach.</p><h3>Problem 1: Maximum Sum Subarray of Size K</h3><p><strong>Problem Statement:</strong> Given an array of integers and a number k, find the maximum sum of any contiguous subarray of size k.</p><h3>The Naive Approach</h3><p>Our first instinct might be to check every possible subarray of size k:</p><pre>public int maxSubarraySum(int[] arr, int k) {<br>    int res = 0;<br>    for(int i = 0; i &lt;= arr.length - k; i++){<br>        int left = i;<br>        int right = i + k;<br>        int temp = 0;<br>        while(left &lt; right){<br>            temp += arr[left];<br>            left++;<br>        }<br>        res = Math.max(res, temp);<br>    }<br>    return res;<br>}</pre><p><strong>Time Complexity:</strong> O(n × k) ≈ O(n²)</p><p>This works, but we’re recalculating sums from scratch for overlapping subarrays. There’s significant redundancy here.</p><h3>The Sliding Window Optimization</h3><p>The key insight: when we move from one subarray to the next, we only need to:</p><ul><li>Remove the element that’s leaving the window</li><li>Add the element that’s entering the window</li></ul><p><strong>Algorithm:</strong></p><ol><li>Calculate the sum of the first k elements (initial window)</li><li>Slide the window one position at a time</li><li>For each slide: add the new element, subtract the departing element</li><li>Track the maximum sum encountered</li></ol><pre>public int maxSubarraySum(int[] arr, int k) {<br>    int res = 0;<br>    // Calculate first window sum<br>    for(int i = 0; i &lt; k; i++){<br>        res += arr[i];<br>    }<br>    <br>    int windowSum = res;<br>    <br>    // Slide the window<br>    for(int i = k; i &lt; arr.length; i++){<br>        windowSum += arr[i];        // Add new element<br>        windowSum -= arr[i - k];    // Remove old element<br>        res = Math.max(res, windowSum);<br>    }<br>    return res;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQqq3dkj0Iw0plqICXLzPg.png" /></figure><p><strong>Time Complexity:</strong> O(n)<br> <strong>Space Complexity:</strong> O(1)</p><p>This is a <strong>fixed-size sliding window</strong> since k remains constant.</p><h3>Problem 2: Permutation in String</h3><p><strong>Problem Statement:</strong> Given two strings s1 and s2, determine if s2 contains any permutation of s1 as a contiguous substring.</p><p><strong>Example:</strong></p><ul><li>s1 = “abc”</li><li>s2 = “educba”</li><li>Result: true (because “cba” is a permutation of “abc”)</li></ul><h3>Understanding Permutations</h3><p>The permutations of “abc” are: abc, acb, bac, bca, cab, cba. Rather than generating all permutations (factorial time complexity!), we can use a clever observation: <strong>two strings are permutations of each other if they have identical character frequency distributions</strong>.</p><h3>The Sliding Window Solution</h3><p>We maintain two frequency arrays:</p><ul><li><strong>Array a:</strong> Character frequencies in s1 (our target)</li><li><strong>Array b:</strong> Character frequencies in the current window of s2</li></ul><p><strong>Algorithm:</strong></p><ol><li><strong>Initial Setup:</strong></li></ol><ul><li>Count all characters in s1 → store in array a</li><li>Count the first len(s1) characters in s2 → store in array b</li></ul><p><strong>2. Sliding Phase:</strong></p><ul><li>For each position from index len(s1) to end of s2:</li><li>Check if current window matches s1’s frequency</li><li>If yes → return true</li><li>Slide window: add new character, remove departing character</li></ul><p><strong>3. Final Check:</strong> Check the last window position</p><p><strong>4. Return false</strong> if no match found</p><pre>class Solution {<br>    public boolean checkInclusion(String s1, String s2) {<br>        int x = s1.length();<br>        int y = s2.length();<br>        if(x &gt; y) return false;<br>        int[] a = new int[26];  // Frequency map for s1<br>        int[] b = new int[26];  // Frequency map for current window<br>        // Build initial window<br>        for (int i = 0; i &lt; x; i++) {<br>            a[s1.charAt(i) - &#39;a&#39;]++;<br>            b[s2.charAt(i) - &#39;a&#39;]++;<br>        }<br>        // Slide the window across s2<br>        for (int i = x; i &lt; y; i++) {<br>            if (matches(a, b))<br>                return true;<br>            b[s2.charAt(i) - &#39;a&#39;]++;      // Add new character<br>            b[s2.charAt(i - x) - &#39;a&#39;]--;  // Remove old character<br>        }<br>        return matches(a, b);  // Check final window<br>    }<br>    private boolean matches(int[] a, int[] b) {<br>        for (int i = 0; i &lt; 26; i++) {<br>            if (a[i] != b[i])<br>                return false;<br>        }<br>        return true;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcUbZDMRd3TXOuQbunspAw.png" /></figure><p><strong>Time Complexity:</strong> O(n + 26k) ≈ O(n) where n is length of s2<br> <strong>Space Complexity:</strong> O(1) (fixed-size arrays of 26 elements)</p><h3>Key Takeaways</h3><p>The sliding window technique shines when:</p><ul><li>You need to examine contiguous subarrays/substrings</li><li>There’s overlap between consecutive windows</li><li>You can incrementally update the window state</li></ul><p>By maintaining state and updating it incrementally instead of recalculating from scratch, we achieve dramatic performance improvements — transforming quadratic solutions into linear ones.</p><p><strong>Practice Tip:</strong> When you see “contiguous” or “substring” in a problem, consider whether a sliding window approach might apply!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c4f7e355f5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2: Mastering the Two Pointers Pattern]]></title>
            <link>https://medium.com/@karthikeswar_/day-2-56-two-pointers-v1-73f61d0e066a?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f61d0e066a</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 09:14:07 GMT</pubDate>
            <atom:updated>2026-02-08T11:21:39.640Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Exploring efficient solutions to Valid Palindrome, 3Sum, and Container with Most Water</em></p><p>The two pointers technique is a powerful algorithmic pattern that can dramatically reduce both time and space complexity. Today, I’ll walk through three classic LeetCode problems that demonstrate when and how to apply this approach effectively.</p><h3><a href="https://leetcode.com/problems/valid-palindrome/description/">Valid Palindrome</a></h3><h3>Initial Approach</h3><pre>public boolean isPalindrome(String s) {<br>    String str = s.toLowerCase().replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;);<br>    for (int i = 0; i &lt; str.length()/2; i++) {<br>        if(str.charAt(i) != str.charAt(str.length()-1-i))<br>            return false;<br>    }<br>    return true;<br>}</pre><p>While this solution works with O(n) time complexity, it has a critical drawback: <strong>O(n) space complexity</strong> from creating a cleaned copy of the string.</p><h3>Optimized Two Pointer Solution</h3><p>We can eliminate the extra space by processing characters in-place with two pointers:</p><pre>public boolean isPalindrome(String s) {<br>    int left = 0;<br>    int right = s.length() - 1;<br>    <br>    while(left &lt; right) {<br>        char l = s.charAt(left);<br>        char r = s.charAt(right);<br>        <br>        if(!Character.isLetterOrDigit(l)) {<br>            left++;<br>        } else if(!Character.isLetterOrDigit(r)) {<br>            right--;<br>        } else {<br>            if(Character.toLowerCase(l) != Character.toLowerCase(r))<br>                return false;<br>            left++;<br>            right--;<br>        }<br>    }<br>    return true;<br>}</pre><p>This approach maintains <strong>O(1) space complexity</strong> by skipping invalid characters on-the-fly rather than preprocessing the entire string.</p><h3><a href="https://leetcode.com/problems/3sum/">3Sum</a></h3><p>The 3Sum problem asks us to find all unique triplets in an array that sum to zero. This is a natural extension of the classic Two Sum problem, but with an added dimension of complexity.</p><h3>Complexity Analysis</h3><ul><li><strong>Brute force</strong> (three nested loops): O(n³) — unacceptable for larger inputs</li><li><strong>HashMap approach</strong>: O(n²) time with O(n) space</li><li><strong>Two pointers with sorting</strong>: O(n²) time with O(log n) space ✓</li></ul><h3>The Solution</h3><pre>public List&lt;List&lt;Integer&gt;&gt; threeSum(int[] nums) {<br>    List&lt;List&lt;Integer&gt;&gt; result = new ArrayList&lt;&gt;();<br>    Arrays.sort(nums);<br>    <br>    for(int i = 0; i &lt; nums.length - 2; i++) {<br>        // Skip duplicate values for the first element<br>        if(i &gt; 0 &amp;&amp; nums[i] == nums[i-1]) {<br>            continue;<br>        }<br>        <br>        int left = i + 1;<br>        int right = nums.length - 1;<br>        <br>        while(left &lt; right) {<br>            int sum = nums[i] + nums[left] + nums[right];<br>            <br>            if(sum == 0) {<br>                result.add(Arrays.asList(nums[i], nums[left], nums[right]));<br>                // Skip duplicates for left and right pointers<br>                while(left &lt; right &amp;&amp; nums[left] == nums[left + 1]) left++;<br>                while(left &lt; right &amp;&amp; nums[right] == nums[right - 1]) right--;<br>                left++;<br>                right--;<br>            } else if(sum &lt; 0) {<br>                left++;<br>            } else {<br>                right--;<br>            }<br>        }<br>    }<br>    return result;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iNnUILkACRoeZDgto7v3w.png" /></figure><p><strong>Key insight</strong>: Sorting the array enables us to use two pointers to efficiently search for complementary pairs, while careful duplicate handling ensures we only collect unique triplets.</p><h3><a href="https://leetcode.com/problems/container-with-most-water/">Container With Most Water</a></h3><p>The area between two lines is determined by: <strong>width × minimum height</strong>.</p><pre>public int maxArea(int[] height) {<br>    int max = 0;<br>    int left = 0;<br>    int right = height.length - 1;<br>    <br>    while(left &lt; right) {<br>        int width = right - left;<br>        int area = Math.min(height[left], height[right]) * width;<br>        max = Math.max(max, area);<br>        <br>        // Move the pointer at the shorter height<br>        if(height[left] &lt; height[right]) {<br>            left++;<br>        } else {<br>            right--;<br>        }<br>    }<br>    return max;<br>}</pre><p>We start with maximum width. Since area depends on the shorter height, we move the pointer at the shorter line inward, seeking a potentially taller line that could increase the area despite reducing width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bz4dpeIIICgQoDPAkZHzXg.png" /></figure><h3>Key Takeaways</h3><p>The two pointers pattern shines when:</p><ul><li>Working with sorted or sortable data</li><li>Searching for pairs or triplets with specific properties</li><li>Optimizing problems that would otherwise require nested loops</li><li>Reducing space complexity by processing data in-place</li></ul><p>Each problem demonstrates a slightly different application of the pattern, but the core principle remains: <strong>intelligently moving two pointers based on problem-specific logic can transform brute-force solutions into elegant, efficient algorithms</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f61d0e066a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1: Mastering Arrays & Hashing]]></title>
            <link>https://medium.com/@karthikeswar_/day-1-8-week-backend-blueprint-v1-f1984553a970?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1984553a970</guid>
            <category><![CDATA[product-of-array]]></category>
            <category><![CDATA[two-sum]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[contains-duplicate]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 08:08:25 GMT</pubDate>
            <atom:updated>2026-02-08T11:21:21.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>Coding Problem Solving — Arrays &amp; Hashing</h3><p>As part of my 8-week backend blueprint, I’m revisiting core data structures and problem-solving patterns. Day 1 focuses on <strong>Arrays &amp; Hashing</strong> using three classic LeetCode problems that every developer should know.</p><p>These problems might seem simple on the surface, but they introduce critical concepts around time complexity, space trade-offs, and hash-based lookups that are essential for writing efficient code.</p><h3>Problem 1: <a href="https://leetcode.com/problems/two-sum/description/">Two Sum</a></h3><h3>The Challenge</h3><p>Given an array of integers and a target value, return the indices of the two numbers that add up to the target.</p><h3>Approach 1: Brute Force</h3><p>The most straightforward solution checks every possible pair using nested loops.</p><pre>private static int[] bruteForce(int[] nums, int target) {<br>    int[] res = new int[2];<br>    int iter = 0;<br>    for (int i = 0; i &lt; nums.length; i++) {<br>        for (int j = 1; j &lt; nums.length; j++) {<br>            iter++;<br>            if (i != j &amp;&amp; nums[i] + nums[j] == target) {<br>                res[0] = i;<br>                res[1] = j;<br>            }<br>        }<br>    }<br>    System.out.println(&quot;brute force iterations = &quot; + iter);<br>    return res;<br>}</pre><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n²)</li><li>Space: O(1)</li></ul><p>This works, but performs unnecessary comparisons and becomes inefficient as the array grows.</p><h3>Approach 2: Refined Brute Force</h3><p>We can optimize slightly by starting the inner loop from i + 1, which avoids:</p><ul><li>Repeating the same pair twice (nums[3] + nums[4] and nums[4] + nums[3])</li><li>Comparing an element with itself</li></ul><pre>private static int[] bruteForceRefined(int[] nums, int target) {<br>    int iter = 0;<br>    for (int i = 0; i &lt; nums.length; i++) {<br>        for (int j = i + 1; j &lt; nums.length; j++) {<br>            iter++;<br>            if (nums[i] + nums[j] == target) {<br>                System.out.println(&quot;brute force refined iterations = &quot; + iter);<br>                return new int[]{i, j};<br>            }<br>        }<br>    }<br>    return new int[]{-1, -1};<br>}</pre><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n²) — still quadratic, just fewer iterations</li><li>Space: O(1)</li></ul><h3>Approach 3: Optimal Solution with HashMap</h3><p>We can solve this in a single pass using a HashMap.</p><p><strong>The Strategy:</strong></p><ol><li>Traverse the array once</li><li>For each element, calculate complement = target - current</li><li>Check if the complement exists in the map</li><li>If yes, we’ve found our pair!</li></ol><pre>private static int[] twoSumHashMap(int[] nums, int target) {<br>    int iter = 0;<br>    Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>    <br>    for (int i = 0; i &lt; nums.length; i++) {<br>        iter++;<br>        int complement = target - nums[i];<br>        <br>        if (map.containsKey(complement)) {<br>            System.out.println(&quot;hash map iterations = &quot; + iter);<br>            return new int[]{map.get(complement), i};<br>        }<br>        <br>        map.put(nums[i], i);<br>    }<br>    <br>    return new int[]{-1, -1};<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmCum448D1f4njJ0myMnLA.png" /></figure><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n) — single pass through the array</li><li>Space: O(n) — HashMap storage</li></ul><p>This is the solution you want in interviews and production code.</p><h3>Problem 2: <a href="https://leetcode.com/problems/contains-duplicate/">Contains Duplicate</a></h3><h3>The Challenge</h3><p>Given an integer array, return true if any value appears at least twice; otherwise, return false.</p><h3>The Efficient Approach: HashSet</h3><p>Since we only care about existence (not indices or counts), a HashSet is perfect for this problem.</p><p><strong>Key Insight:</strong> HashSet.add() returns false if the element already exists.</p><pre>private static boolean isDuplicatePresent(int[] nums) {<br>    Set&lt;Integer&gt; seen = new HashSet&lt;&gt;();<br>    <br>    for (int num : nums) {<br>        if (!seen.add(num)) {<br>            return true;<br>        }<br>    }<br>    <br>    return false;<br>}</pre><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n)</li><li>Space: O(n)</li></ul><h3>Problem 3: <a href="https://leetcode.com/problems/product-of-array-except-self/">Product of Array Except Self</a></h3><h3>The Challenge</h3><p>Given an array nums, return an array where answer[i] is the product of all elements except nums[i].</p><p><strong>Constraints:</strong></p><ul><li>Must run in O(n) time</li><li>Cannot use division operation</li></ul><h3>The Solution: Prefix and Suffix Products</h3><p>Since nested loops aren’t viable and division is off the table, we use a clever two-pass approach:</p><ol><li>First pass: Calculate prefix products (products of all elements before current)</li><li>Second pass: Multiply by suffix products (products of all elements after current)</li></ol><pre>public static int[] productExceptSelf(int[] nums) {<br>    int[] answer = new int[nums.length];<br>    <br>    // First pass: build prefix products<br>    answer[0] = 1;<br>    for (int i = 1; i &lt; nums.length; i++) {<br>        answer[i] = answer[i - 1] * nums[i - 1];<br>    }<br>    <br>    // Second pass: multiply by suffix products<br>    int suffixProduct = 1;<br>    for (int i = nums.length - 1; i &gt;= 0; i--) {<br>        answer[i] *= suffixProduct;<br>        suffixProduct *= nums[i];<br>    }<br>    <br>    return answer;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAGXjWVrlA0dA6WagKDepA.jpeg" /></figure><p><strong>Complexity Analysis:</strong></p><ul><li>Time: O(n) — two passes, still linear</li><li>Space: O(1) — if we don’t count the output array</li></ul><h3>Key Takeaways</h3><p><strong>Brute force solutions</strong> help you understand the problem but rarely scale in production environments.</p><p><strong>Small optimizations</strong> can significantly reduce unnecessary work, though they might not change the Big O complexity.</p><p><strong>Hashing is powerful</strong> for achieving linear-time solutions where brute force would require O(n²).</p><p><strong>Choose the right data structure</strong>: HashMap when you need key-value pairs, HashSet when you only care about membership.</p><p><strong>Prefix/suffix patterns</strong> are your friend when problems ask for “everything except self” without allowing division.</p><p>These three problems form the foundation of array manipulation and hashing techniques. Master them, and you’ll have a solid toolkit for tackling more complex challenges.</p><p><strong>What’s your go-to approach for optimizing nested loops? Drop a comment below!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1984553a970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick reference guide to GIT COMMANDS]]></title>
            <link>https://medium.com/@karthikeswar_/git-commands-b243a58ac58a?source=rss-834db34ecc77------2</link>
            <guid isPermaLink="false">https://medium.com/p/b243a58ac58a</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Karthik]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 08:39:57 GMT</pubDate>
            <atom:updated>2022-06-14T04:08:04.013Z</atom:updated>
            <content:encoded><![CDATA[<p>A go to quick reference guide for frequently used git commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVmNminek4CEH48iAeAsvw.png" /></figure><blockquote>Clone the branch from repo url</blockquote><p>git clone -b <strong><em>branch_name</em></strong> <strong><em>url</em></strong></p><blockquote>Shows me changed files</blockquote><p>git status</p><blockquote>Change to other branch</blockquote><p>git switch <strong>branch_name</strong></p><blockquote>Get me all the changes from repo</blockquote><p>git fetch</p><blockquote>Pull the changes from specific branch</blockquote><p>git pull origin <strong>branch_name</strong></p><blockquote>In which branch am I checked into</blockquote><p>git branch</p><blockquote>Add all changed files</blockquote><p>git add .</p><blockquote>Add only mentioned files</blockquote><p>git add <strong>“&lt;filename1&gt;” “&lt;filename2&gt;”</strong></p><blockquote>Commit the added files</blockquote><p>git commit -m <strong>“Commit message”</strong></p><blockquote>Push the commit/s into current checked in branch <em>🅿️</em></blockquote><p>git push</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o72FgwyBxqGxxrsRy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsporzaredactie-euro2016-sporza-3o72FgwyBxqGxxrsRy&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F3o72FgwyBxqGxxrsRy%2Fgiphy.gif%3Fcid%3D790b76118c91fcd4f6a8809883df5ebe4dde0df5dc35bbac%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="238" frameborder="0" scrolling="no"><a href="https://medium.com/media/31be65f039596398a6cd2b0f400c039a/href">https://medium.com/media/31be65f039596398a6cd2b0f400c039a/href</a></iframe><blockquote>Revert the changes from commitId <em>↩️</em></blockquote><p>git revert -m 1 <strong>“commitId”</strong></p><blockquote>Cherry pick a particular commit and add to current checked in branch <em>🍒</em></blockquote><p>git cherry-pick <strong>“commitId”</strong></p><blockquote>Abort the current merge <em>🛑</em></blockquote><p>git merge — abort</p><blockquote>Set git username</blockquote><p>git config — global user.name <strong>“username”</strong></p><blockquote>Set git mail</blockquote><p>git config — global user.email <strong>“example@gmail.com”</strong></p><blockquote>Set git password</blockquote><p>git config — global user.password <strong>“secret”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b243a58ac58a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>