<?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 Sachin Sarvesh on Medium]]></title>
        <description><![CDATA[Stories by Sachin Sarvesh on Medium]]></description>
        <link>https://medium.com/@sarvesh240698?source=rss-fad643e62169------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nn9DU1qdN6_u8rR6_4v3kA.jpeg</url>
            <title>Stories by Sachin Sarvesh on Medium</title>
            <link>https://medium.com/@sarvesh240698?source=rss-fad643e62169------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:15:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarvesh240698/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[Java : Remove Duplicates from Sorted Array]]></title>
            <link>https://medium.com/@sarvesh240698/java-remove-duplicates-from-sorted-array-37c53e33e95a?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c53e33e95a</guid>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 09:16:44 GMT</pubDate>
            <atom:updated>2026-04-25T09:16:44.462Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/?envType=problem-list-v2&amp;envId=array">Leet Code Link</a> | Difficulty : Easy</p><p><strong>About the problem :</strong> We are given a sorted integer array and we need to remove duplicates in-place, returning k — the count of unique elements.</p><p><strong>Problem approach 1 : HashMap</strong></p><ol><li>Create an empty HashMap and a pointer j starting at 0.</li><li>Iterate through the array — if the current element is not already in the map, add it and write it to nums[j], then increment j.</li><li>The map acts as a seen-tracker; duplicates are simply skipped.</li><li>Return j as the count of unique elements.</li></ol><pre>private static int removeDuplicates(int[] nums) {<br>    Map&lt;Integer, Integer&gt; map = new HashMap&lt;&gt;();<br>    int j = 0;<br>    for (int i = 0; i &lt; nums.length; i++) {<br>        if (!map.containsKey(nums[i])) {<br>            map.put(nums[i], i);<br>            nums[j++] = nums[i];<br>        }<br>    }<br>    return j;<br>}</pre><p><strong>Problem approach 2 : Two Pointers</strong> (As the array is already sorted, no extra space needed)</p><ol><li>We keep a slow pointer x at 0 and pointer i to iterate entirely.</li><li>Since the array is sorted, any element greater than nums[x] is guaranteed to be the next unique value.</li><li>We write it to nums[++x] and keep going.</li><li>One pass, O(1) space.</li></ol><pre>private static int removeDuplicatesOptimised(int[] nums) {<br>    int x = 0;<br>    for (int i = 0; i &lt; nums.length; i++) {<br>        if (nums[i] &gt; nums[x]) {<br>            nums[++x] = nums[i];<br>        }<br>    }<br>    return x + 1;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c53e33e95a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Remove Element]]></title>
            <link>https://medium.com/@sarvesh240698/java-remove-element-5000b75f21de?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/5000b75f21de</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 06:18:00 GMT</pubDate>
            <atom:updated>2026-04-22T06:18:00.361Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/remove-element/description/?envType=problem-list-v2&amp;envId=array">Leet Code Link</a> | Difficulty : Easy</p><p><strong>About the problem :</strong> We are given an integer array and a value val. We need to remove all occurrences of val in-place and return k, the count of elements that are not equal to val.</p><p><strong>Problem approach 1 : Two Pointer</strong></p><ol><li>Keep a slow pointer x starting at 0 — it tracks the position to write the next valid element.</li><li>Iterate through the array with i. Whenever nums[i] is not equal to val, write it to nums[x] and increment x.</li><li>Elements equal to val are simply skipped, no extra space needed.</li><li>Return x as the count of remaining elements.</li></ol><pre>private static int removeElement(int[] nums, int val) {<br>        int x = 0;<br>        for (int i = 0; i &lt; nums.length; i++) {<br>            if (nums[i] != val) {<br>                nums[x] = nums[i];<br>                x++;<br>            }<br>        }<br>        return x;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5000b75f21de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : FourSum]]></title>
            <link>https://medium.com/@sarvesh240698/java-foursum-331d3317a7b4?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/331d3317a7b4</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 04:55:00 GMT</pubDate>
            <atom:updated>2026-04-20T04:55:00.364Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/4sum?envType=problem-list-v2&amp;envId=array">Leet Code Link </a>| Difficulty : Med</p><p><strong>About the problem : </strong>This problem is an extension of ThreeSum approach. We are given an integer array and a target integer. We need to find all unique quadruplets in the array that sum up to the target.</p><p><strong>Solution : </strong>Sort the array, fix two elements with nested loops, and use two pointers for the remaining pair.</p><p><strong>Core part :</strong></p><ol><li>We fix i and j with two outer loops, then run left and right pointers inward for each pair.</li><li>Two early-exit checks at the start avoid unnecessary work.If even the four smallest elements exceed target, or the four largest fall short, we return immediately.</li><li>After a match, we check for duplicate elements and skip them before moving the pointers.</li></ol><p>Note :</p><p>As the constraint says values can reach up to 2⁹ range. Four such values multiplied together can overflow a 32-bit int, so the sum is cast to long to handle it safely.</p><pre>    private static List&lt;List&lt;Integer&gt;&gt; fourSum(int[] nums, int target) {<br>        int n = nums.length;<br>        if (n &lt; 4) return new ArrayList&lt;&gt;();<br><br>        Arrays.sort(nums);<br>        if((long)nums[0] + nums[1] + nums[2] + nums[3] &gt; target) return new ArrayList&lt;&gt;();<br>        if(((long)nums[n-1] + nums[n-2] + nums[n-3] + nums[n-4]) &lt; target) return new ArrayList&lt;&gt;();<br><br>        List&lt;List&lt;Integer&gt;&gt; result = new LinkedList&lt;&gt;();<br>        for(int i =0; i&lt;n-3;i++){<br>            if(i &gt; 0 &amp;&amp; nums[i] == nums[i-1]) continue;<br><br>            for(int j=i+1; j&lt;n-2;j++){<br>                if(j &gt; i+1 &amp;&amp; nums[j] == nums[j-1]) continue;<br><br>                int left = j+1;<br>                int right = n-1;<br><br>                while(left &lt; right){<br>                    long sum = (long)nums[i] + nums[j] + nums[left] + nums[right];<br>                    if(sum ==target){<br>                        result.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right] ));<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>                        right --;<br>                        left ++;<br>                    }else if(sum &lt; target) left++;<br>                    else right --;<br>                }<br>            }<br>        }<br>        return result;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=331d3317a7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : ThreeSumClosest]]></title>
            <link>https://medium.com/@sarvesh240698/java-threesumclosest-62f2ef61932e?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f2ef61932e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[practise]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 03:44:58 GMT</pubDate>
            <atom:updated>2026-04-15T03:44:58.055Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/3sum-closest/?envType=problem-list-v2&amp;envId=array">Leet Code link</a> | Difficulty : Medium</p><p>This is an extension of Three Sum problem</p><p><strong>About the problem :</strong> We are given an integer array and a target integer. We need to find three elements in the array whose sum is closest to the target and return that sum.</p><p><strong>Solution </strong>: : Sort the array, fix one element, and use two pointers in the remaining sub array to find the closest sum.</p><p><strong>Core part :</strong></p><ol><li>We sum the result with the first triplet sum.</li><li>For each itr, we move left and right inward updating result whenever the current sum is closer to target.</li><li>If sum equals target we return immediately, if sum &lt; target we move left up, else we move right down.</li></ol><pre>private static int threeSumCloset(int[] num, int target) {<br>        Arrays.sort(num);<br>        int n = num.length;<br>        int result = num[0] + num[1] + num[2];<br><br>        for(int i =0; i &lt; n-2; i++){<br>            int left = i+1;<br>            int right = n-1;<br><br>            while(left &lt; right){<br>                int sum = num[i] + num[left] + num[right];<br><br>                if(Math.abs(target-sum) &lt; Math.abs(target-result)){<br>                    result =sum;<br>                }<br>                if (sum==target) return target;<br>                else if (sum&lt; target) left ++;<br>                else right --;<br>            }<br>        }<br><br>        return result;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f2ef61932e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : ThreeSum]]></title>
            <link>https://medium.com/@sarvesh240698/java-threesum-120bb22faf42?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/120bb22faf42</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[motivation]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 03:32:32 GMT</pubDate>
            <atom:updated>2026-04-13T03:32:32.078Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/3sum/description/?envType=problem-list-v2&amp;envId=array">Leetcode link</a> | Difficulty : Medium</p><p><strong>About the problem : </strong>We are given an integer array and we need to find all unique triplets in the array that sum up to the given target. (2 approaches for this problem)</p><p><strong>Problem approach 1 : Brute Force</strong></p><ol><li>Use three nested loops to check all possible triplets in the array.</li><li>If the sum of the three elements equals zero, sort the triplet and add it to a HashSet.</li><li>The HashSet handles duplicates automatically .</li></ol><pre>private static void threeSumBruteForce(int[] nums) {<br>        int sum = 0;<br>        Set&lt;List&lt;Integer&gt;&gt; unique_triplets = new HashSet&lt;&gt;();<br>        for(int i = 0 ; i &lt; nums.length ; i++){<br>            for(int j = i+1; j&lt; nums.length ; j++){<br>                for(int k = j+1; k &lt;nums.length;k++) {<br>                    sum = nums[i] + nums[j] + nums[k];<br>                    if (sum == 0) {<br>                        int[] triplets = {nums[i] , nums[j] , nums[k]};<br>                        Arrays.sort(triplets);<br>                        unique_triplets.add(Arrays.asList(triplets[0],triplets[1],triplets[2]));<br>                    }<br>                }<br>            }<br>        }<br>        System.out.println(unique_triplets);<br>    }</pre><p><strong>Solution 2 : </strong>Optimised with Sorting and Two Pointers. Sort the array, fix one element, and use two pointers to find the remaining pair.</p><p><strong>Core part : </strong>After sorting, for each index i we set left = i+1 and right = end, then move them inward based on the sum vs target. Duplicate skipping is handled by checking adjacent elements after each valid triplet is found.</p><pre>    private static List&lt;List&lt;Integer&gt;&gt; threeSum(int[] nums) {<br>        List&lt;List&lt;Integer&gt;&gt; res = new ArrayList&lt;&gt;();<br>        int size = nums.length;<br>        if (size &lt; 3) return res;<br><br>        Arrays.sort(nums);<br><br>        for(int i=0; i &lt; size-2; i++ ){<br>            if(i&gt;0 &amp;&amp; nums[i] == nums[i-1]) continue;<br>            if(nums[i] &gt; 0) break;<br><br>            int left = i + 1;<br>            int right = size - 1;<br>            int target = - nums[i];<br><br>            while(left &lt; right){<br>                int sum = nums[left] + nums[right];<br>                if (sum == target){<br>                    res.add(Arrays.asList(nums[i],nums[left],nums[right]));<br>                    right --;<br>                    left ++;<br><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>                }else if(sum&gt;target){<br>                    right--;<br>                }else {<br>                    left++;<br>                }<br>            }<br>        }<br>        return res;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=120bb22faf42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Next Greater Element]]></title>
            <link>https://medium.com/@sarvesh240698/java-next-greater-element-d759f578ee9a?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/d759f578ee9a</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 14:56:38 GMT</pubDate>
            <atom:updated>2026-04-09T14:56:38.470Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>About the problem :</strong> We are given an integer array and for each element we need to find the next greater element to its right; if none exists, return -1 for that position. (2 approaches for this problem)</p><p><strong>Solution 1 : Brute Force</strong></p><ol><li>Loop through each element in the array.</li><li>For every element, run an inner loop from the next index to the end.</li><li>Find the first element greater than the current one and store it in result.</li><li>If no greater element is found, store -1.</li></ol><pre>private static int[] findNextGreaterBrute(int[] arr) {<br>    int n = arr.length;<br>    int[] result = new int[n];<br>    for (int i = 0; i &lt; n; i++) {<br>        result[i] = -1;<br>        for (int j = i + 1; j &lt; n; j++) {<br>            if (arr[j] &gt; arr[i]) {<br>                result[i] = arr[j];<br>                break;<br>            }<br>        }<br>    }<br>    return result;<br>}</pre><p><strong>Solution 2 (Optimised via Stack) :</strong> Iterate from right to left, using a stack to track the element and check for greater element.</p><p><strong>Core part :</strong></p><ol><li>We iterate from the end of the array. For each element, we pop stack elements that are smaller or equal, they can never be the next greater for anything to the left.</li><li>Whatever remains on top is the answer; then we push the current element for future lookups.</li><li>If not greater element is found, we add -1.</li></ol><pre>private static int[] findNextGreater(int[] arr) {<br>        int n = arr.length;<br>        int[] result = new int[n];<br><br>        Stack&lt;Integer&gt; stack = new Stack&lt;&gt;();<br>        for (int i = n - 1; i &gt;= 0; i--) {<br>            while (!stack.isEmpty() &amp;&amp; stack.peek() &lt;= arr[i]) {<br>                stack.pop();<br>            }<br>            result[i] = stack.isEmpty() ? -1 : stack.peek();<br>            stack.push(arr[i]);<br>        }<br>        return result;<br>    }</pre><p>Note : It was an interview L1 round question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d759f578ee9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Longest Common Prefix]]></title>
            <link>https://medium.com/@sarvesh240698/java-longest-common-prefix-b2ce45c72ff1?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ce45c72ff1</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 11:34:48 GMT</pubDate>
            <atom:updated>2026-04-08T11:34:48.126Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/longest-common-prefix/description/?envType=problem-list-v2&amp;envId=array">Leet Code link </a>| Difficulty : Easy</p><p><strong>About the problem</strong> : We are given an array of strings and we need to find the longest common prefix among all the strings. If there is none, return an empty string. (3 approaches for this problem)</p><p><strong>Solution 1 : </strong>Start with the first string as the prefix and keep trimming it until every other string starts with it.</p><p><strong>Core part :</strong> We use indexOf to check if the current prefix exists at position 0 of each string. If not, we chop off the last character and retry until it either matches or becomes empty.</p><pre>    /* Version 1<br>    Time: O(n * m²) (substring operations costly)<br>    Space: O(1)<br>     */<br>    private static String findPrefix_v1(String[] str) {<br>        if (str == null || str.length == 0) return null;<br>        String prefix = str[0];<br><br>        for(int i = 1; i &lt; str.length; i++){<br>            while(str[i].indexOf(prefix) !=0){<br>                prefix = prefix.substring(0,prefix.length()-1);<br><br>                if (prefix.isEmpty()) return &quot;&quot;;<br>            }<br>        }<br>        return prefix;<br>    }</pre><p><strong>Solution 2 (Best approach) : </strong>Compare character by character across all strings at the same index.</p><p><strong>Core part : </strong>We iterate each character index of the first string and check if every other string has the same character at that position. The moment there’s a mismatch or we go out of bounds on any string, we return the prefix up to that point.</p><pre>/*<br>    Version 2<br>    Time: O(n * m)<br>    Space: O(1)<br>     */<br>    private static String findPrefix_v2(String[] str) {<br>        if(str == null || str.length ==0) return &quot;&quot;;<br><br>        for(int i =0; i &lt; str[0].length();i++){<br>            char ch = str[0].charAt(i);<br><br>            for(int j=1; j&lt; str.length;j++){<br>                if(i &gt;= str[j].length() || str[j].charAt(i) != ch){<br>                    return str[0].substring(0,i);<br>                }<br>            }<br>        }<br>        return str[0];<br>    }</pre><p><strong>Solution 3 </strong>: (Sort + Compare — O(n log n + m)) — Sort the array and compare the first and last strings.</p><p><strong>Core part :</strong> After sorting, the most different strings are located at the two ends. So the common prefix of the entire array is just the common prefix between the first and last string — we iterate each characters to find the prefix.</p><pre>    /*<br>    Version 3<br>    Time: O(n log n + m) (due to sorting)<br>    Space: O(1)<br>    */<br>    private static String findPrefix_v3(String[] str) {<br>        if(str == null || str.length == 0) return &quot;&quot;;<br><br>        Arrays.sort(str);<br>        String first = str[0];<br>        String last = str[str.length -1];<br>        int i = 0 ;<br><br>        while(i &lt; first.length() &amp;&amp; i &lt; last.length()){<br>            if(first.charAt(i) != last.charAt(i)) break;<br>            i++;<br>        }<br><br>        return first.substring(0,i);<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ce45c72ff1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Container with most water]]></title>
            <link>https://medium.com/@sarvesh240698/java-container-with-most-water-327ceddd7691?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/327ceddd7691</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 05:12:47 GMT</pubDate>
            <atom:updated>2026-04-07T05:12:47.725Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/container-with-most-water/description/?envType=problem-list-v2&amp;envId=array">Leet Code link</a> | Difficulty : Medium</p><p><strong>About the problem : </strong>We will be given an array of integers and we should consider each element as a wall or container. Now we need to find out the the combination of containers that can hold highest volume of water.</p><p><strong>Problem approach 1 : Brute force method</strong></p><ol><li>We use two loops to check every possible pair of lines.</li><li>For each pair (i, j), the water held is determined by the shorter line multiplied by the distance between them — min(height[i], height[j]) * (j - i).</li><li>We keep track of the maximum capacity and capacity found across all pairs, compare at every iteration and return the maximum capacity.</li></ol><pre>private static int mostWaterBruteForce(int[] containers) {<br>        int max_capacity = 0;<br>        int arr_length = containers.length;<br><br>        for (int itr1 = 0; itr1 &lt; arr_length; itr1++) {<br>            for (int itr2 = itr1 + 1; itr2 &lt; arr_length; itr2++) {<br>                int capacity = Math.min(containers[itr1], containers[itr2]) * (itr2 - itr1);<br>                if (capacity &gt; max_capacity) {<br>                    max_capacity = capacity;<br>                }<br>            }<br>        }<br>        return max_capacity;<br>    }</pre><p><strong>Problem approach 2 : Two pointer method (Optimised)</strong></p><ol><li>We can use two pointer method to iterate through the array.</li><li>We need to consider the smallest element as height.</li><li>We need to consider the difference between the elements as length.</li><li>We need two place holder to calculate current capacity and max capacity.</li><li>We initialize both current capacity and max capacity to zero.</li><li>We multiple the length and height and store the value in current capacity.</li><li>Then we compare current capacity with max capacity, and if current capacity is higher we assign it to max capacity.</li><li>By the end of loop, we return max capacity.</li></ol><pre>package LeetCode;<br><br>public class ContainerWithMostWater {<br>    public static void main(String[] args){<br>        int[] containers = {1,8,6,2,5,4,8,3,7};<br>        System.out.println(mostWater(containers));<br>    }<br><br>    private static int mostWater(int[] containers) {<br>        int i =0, j = containers.length-1;<br>        int capacity = 0;<br>        int max_capacity = 0;<br>        while(i&lt;j){<br>            if(containers[i] &gt; containers[j] ){<br>                capacity = containers[j] * (j-i);<br>                j--;<br>            }else{<br>                capacity = containers[i] * (j-i);<br>                i++;<br>            }<br>            if(capacity &gt; max_capacity){<br>                max_capacity = capacity;<br>            }<br>        }<br>        return max_capacity;<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=327ceddd7691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Two Sums]]></title>
            <link>https://medium.com/@sarvesh240698/java-two-sums-9457162e0da2?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/9457162e0da2</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 15:17:49 GMT</pubDate>
            <atom:updated>2026-04-04T15:17:49.603Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/two-sum/?envType=problem-list-v2&amp;envId=array">Leet Code link </a>| Difficulty : Easy</p><p><strong>About the problem : </strong>We will be given an integer array and a target as inputs. We need to find out a combination of two elements in the array that will sum up to the given target. (On condition there is only one pair)</p><p><strong>Problem approach 1: Two pointer (In case of sorted array)</strong></p><ol><li>Here, we can use the two pointer method, one pointer to the left index(first element) and another pointer to the right index(last element).</li><li>Now we add up the two elements of the array(where the pointer is the index), and compare with target.</li><li>If the sum is greater than the target, we can decrement the right pointer.</li><li>If the sum is lesser than the target, we can increment the left pointer.</li><li>By doing this in while loop with condition (left &lt; right), we can easily find the two elements that sum up to the target.</li></ol><pre>public class TwoPointer {<br>    public static void main(String[] args) {<br>        int[] arr = {1, 2, 3, 5, 6};<br>        int target = 6;<br>        System.out.println(Arrays.toString(targettedOutput(arr, target)));<br>    }<br><br>    private static int[] targettedOutput(int[] arr, int target) {<br>        ;<br>        int left = 0;<br>        int right = arr.length - 1;<br><br>        while (left &lt; right) {<br>            if ((arr[left] + arr[right]) &gt; target) right--;<br>            else if ((arr[left] + arr[right]) &lt; target) left++;<br>            else return new int[]{arr[left], arr[right]};<br>        }<br>        return new int[] {};<br>    }<br>}</pre><p><strong>Problem approach 2 : Brute force method</strong></p><ol><li>In this method, we use two iterators with two for loop, to check all the possible pairs.</li><li>We iterate until we find the exact pair.</li></ol><pre>    public static int[] twoSumAndTarget(int[] nums, int target) {<br>        int arr_length = nums.length;<br>        for (int itr1 = 0; itr1 &lt; arr_length; itr1++) {<br>            for (int itr2 = itr1 + 1; itr2 &lt; arr_length; itr2++) {<br>                int sum_of_two_itrs = nums[itr1] + nums[itr2];<br>                if (sum_of_two_itrs == target) {<br>                    System.out.println(&quot;Found the indexes &quot; + itr1 + &quot; , &quot; + itr2);<br>                    return new int[]{itr1, itr2};<br>                }<br>            }<br>        }<br>    }</pre><p><strong>Problem 3 : Using a hashmap — optimised method</strong></p><ol><li>In this method, I will create an empty map in the beginning and then start the iteration.</li><li>I will take the first element of the array via loop, and I will find the complement that needs to add up to the target sum.</li><li>In the same loop, I also check whether the complement already exists in the map as Key. If exists, the index of the complement element is stored as value and I can use the same to return the combination.</li><li>After the check condition, we will add the value of element(first element as itr =0) and iterator in the map for easy reference.</li><li>In the next loops, we can find the pair.</li></ol><pre>    private static int[] twoSumAndTarget(int[] nums, int target) {<br>        HashMap&lt;Integer,Integer&gt; map = new HashMap&lt;&gt;();<br>        for(int itr1 = 0; itr1 &lt; nums.length; itr1++){<br>            int complement = target - nums[itr1];<br>            if(map.containsKey(complement)){<br>                return new int[]{map.get(complement),itr1};<br>            }<br>            map.put(nums[itr1],itr1);<br>        }<br>        return new int[]{};<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9457162e0da2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java : Median of two sorted Array]]></title>
            <link>https://medium.com/@sarvesh240698/median-of-two-sorted-array-1ce067260cc6?source=rss-fad643e62169------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce067260cc6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Sachin Sarvesh]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 04:22:56 GMT</pubDate>
            <atom:updated>2026-04-04T08:14:21.274Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://leetcode.com/problems/median-of-two-sorted-arrays/?envType=problem-list-v2&amp;envId=array">Leet Code link</a> | Difficultly — Hard</p><p><strong>About the problem </strong>: We will be given two sorted arrays as input and we need to find the median of these two arrays (3 approaches for this problem)</p><blockquote>I have briefed about the solution and core path of each solution but I have not explained in detailed as I want the reader to get a gist of each solution approach and do a dry run to understand it entirely.</blockquote><p><strong>Problem approach :</strong></p><p><strong>Solution 1 : </strong>Since it is already sorted, we can merge them into a single array and find the median by iterating inside the array.</p><p><strong>Core part : </strong>We use a condition to sort and merge the two sorted arrays, so that we find the median easily by the middle element.</p><pre>public static void findMedianSortedArrays(int[] nums1, int[] nums2) {<br>        int num1_size = nums1.length;<br>        int num2_size = nums2.length;<br>        int total_length = num1_size + num2_size;<br>        // System.out.printf(&quot;%d %d &quot;,num1_size, num2_size);<br><br>        int[] nums3 = new int[num1_size + num2_size];<br><br>        int i=0, j=0, k=0;<br><br>        while(i &lt; num1_size &amp;&amp; j &lt; num2_size ){<br>            nums3[k++] = nums1[i] &lt; nums2[j] ? nums1[i++] : nums2[j++];<br>        }<br><br>        while (i &lt; num1_size) nums3[k++] = nums1[i++];<br>        while (j &lt; num2_size) nums3[k++] = nums2[j++];<br><br>        // System.out.println(Arrays.toString(nums3));<br><br>        if(total_length%2 !=0){<br>            System.out.println(nums3[total_length/2]);<br>        }else{<br>            System.out.println((nums3[total_length/2 -1] + nums3[total_length/2] )/2.0);<br>        }<br>    }</pre><p><strong>Solution 2 (Size Optimised — O(m+n) ) : </strong>In Solution1, we create a new merged array which will consume space. In this approach, we use pointers to iterate inside the two arrays and find out the median.</p><p><strong>Core part : </strong>We use two placeholders(previous and current) along with iterators to iterate the indexes and use a condition to figure out the median elements.</p><pre>private static void findMedianSpaceOptimised(int[] num1, int[] num2) {<br>        int num1_size = num1.length;<br>        int num2_size = num2.length;<br>        int total_length = num1_size + num2_size;<br><br>        int i =0, j=0, current =0, previous = 0;<br><br>        for(int k=0; k&lt;=total_length/2;k++) {<br>            previous = current;<br>            if (i &lt; num1_size &amp;&amp; (j &gt;= num2_size || num1[i] &lt; num2[j])) {<br>                current = num1[i++];<br>            } else {<br>                current = num2[j++];<br>            }<br>        }<br>        //  System.out.println(previous + &quot; &#39; &quot; + current + &quot;length : &quot; + total_length/2);<br>        if(total_length % 2 != 0){<br>            System.out.println(&quot;inside first&quot; + current);<br>        }else{<br>            System.out.println((previous + current) / 2.0);<br>        }<br><br>    }</pre><p><strong>Solution 3 (Time Optimised — <em>O(log(min(m,n)))</em> ) : </strong>In this solution, we use binary search algorithm to split the two arrays into equal halves.</p><p><strong>Core path :</strong> Here we use 6 placeholders(low, high, maxLeft1, maxLeft2, minRight1, minRight2) and few conditions to identify the medians.</p><pre>public static double findMedianTimeOptimised(int[] nums1, int[] nums2) {<br>        if(nums1.length &gt; nums2.length) return findMedianTimeOptimised(nums2, nums1);<br><br>         int m = nums1.length;<br>         int n = nums2.length;<br>         int low = 0;<br>         int high = m;<br><br>         while(low &lt;= high){<br>             int i = (low + high ) / 2;<br>             int j = (m + n + 1)/2 - i;<br><br>             int maxLeft1 = (i==0) ? Integer.MIN_VALUE :nums1[i-1];<br>             int minRight1 = (i==m) ? Integer.MAX_VALUE : nums1[i];<br><br>             int maxLeft2 = (j==0) ? Integer.MIN_VALUE : nums2[j-1];<br>             int minRight2 = (j ==n) ? Integer.MAX_VALUE : nums2[j];<br><br>             if ((maxLeft1 &lt;= minRight2) &amp;&amp; (maxLeft2 &lt;= minRight1)){<br>                 // System.out.println(&quot;inside main if&quot;);<br>                 if((m+n) % 2 ==0){<br>                     return (Math.max(maxLeft2,maxLeft1) + Math.min(minRight2,minRight1))/2.0;<br>                 } else {<br>                     return Math.max(maxLeft2,maxLeft1);<br>                 }<br>             }else if(maxLeft1 &gt; minRight2){<br>                 // System.out.println(&quot;inside else if&quot;);<br>                 high = i -1;<br>             } else {<br>                 // System.out.println(&quot;inside else&quot;);<br>                 low = i+1;<br>             }<br>         }<br>        return 0.0;<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce067260cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>