<?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 Abhinav Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Abhinav Chauhan on Medium]]></description>
        <link>https://medium.com/@abhinavcj29?source=rss-5fd6638e4624------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5QRB8YARyVyCJNh1Ff_V4w.jpeg</url>
            <title>Stories by Abhinav Chauhan on Medium</title>
            <link>https://medium.com/@abhinavcj29?source=rss-5fd6638e4624------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:54:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhinavcj29/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[Container With Most Water]]></title>
            <link>https://medium.com/@abhinavcj29/container-with-most-water-d3423cf9f18f?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3423cf9f18f</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[alogrithm]]></category>
            <category><![CDATA[container-with-most-water]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 07:00:04 GMT</pubDate>
            <atom:updated>2025-08-31T07:00:34.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1a-s21wBgHr26NUluel-Ng.png" /></figure><p>You are given an array arr of positive integers where each element represents the height of a vertical line on a coordinate plane.</p><p>Your task is to find <strong>two lines</strong> such that together with the x-axis, they form a container that can hold the <strong>maximum amount of water</strong>.</p><p><strong>Example:</strong></p><pre>Input: arr = [1, 5, 4, 3]<br>Output: 6</pre><p>Explanation:</p><p>The best container is formed between lines at index 1 (5) and index 3 (3):</p><ul><li>Height = min(5, 3) = 3</li><li>Width = 3–1 = 2</li><li>Area = 3 × 2 = 6</li></ul><h3>Brute Force Approach (O(n²))</h3><ul><li>Check <strong>all pairs</strong> (i, j) with i &lt; j.</li><li>Compute area = min(arr[i], arr[j]) × (j — i).</li><li>Keep track of maximum.</li></ul><p>This works but is too slow for large arrays.</p><h3>Optimized Two-Pointer Approach (O(n))</h3><h3>Intuition</h3><p>Start with the <strong>widest possible container</strong> (first and last line).</p><p>The area depends on two things:</p><ul><li><strong>Width</strong> = distance between lines.</li><li><strong>Height</strong> = shorter of the two lines.</li></ul><p>If we want to maximize area, we must try to <strong>increase the limiting height</strong>.</p><p>Therefore:</p><ul><li>If left line &lt; right line → move l++ (maybe a taller line appears).</li><li>If right line &lt; left line → move r — .</li></ul><p>Moving the taller side is useless because the shorter side will still limit the area.</p><h3>Algorithm</h3><ul><li>Initialize two pointers: l = 0, r = n-1.</li><li>Compute current area:</li></ul><pre>height = min(arr[l], arr[r])<br>width = r - l<br>area = height * width</pre><ul><li>Update maximum.</li><li>Move the pointer at the shorter line (l++ if arr[l] &lt; arr[r], else r — ).</li><li>Repeat until l &gt;= r.</li></ul><h3>Dry Run Example</h3><p>For arr = [1, 5, 4, 3]</p><ul><li>l=0, r=3 → area = min(1,3) × 3 = 3</li><li>Move left (since 1 &lt; 3).</li><li>l=1, r=3 → area = min(5,3) × 2 = 6</li><li>Move right (since 5 &gt; 3).</li><li>l=1, r=2 → area = min(5,4) × 1 = 4</li></ul><p>Maximum = <strong>6</strong></p><h3>C++ Implementation</h3><pre>class Solution {<br>  public:<br>    int maxWater(vector&lt;int&gt; &amp;arr) {<br>        int n = arr.size();<br>        int l = 0, r = n - 1;<br>        int total = 0;<br>        <br>        while (l &lt; r) {<br>            int height = min(arr[l], arr[r]);<br>            int width = r - l;<br>            total = max(total, height * width);<br>            <br>            // Move the pointer at the shorter line<br>            if (arr[l] &lt; arr[r]) l++;<br>            else r--;<br>        }<br>        return total;<br>    }<br>};</pre><h3>Complexity Analysis</h3><ul><li><strong>Time Complexity:</strong> O(n) → each pointer moves at most once.</li><li><strong>Space Complexity:</strong> O(1) → only a few extra variables.</li></ul><h3>Key Takeaways</h3><ul><li>The <strong>shorter line always limits the area</strong>.</li><li>Moving the taller line inward never increases area.</li><li>Two-pointer approach ensures an <strong>optimal solution in linear time</strong>.</li></ul><p>And that’s it! You now fully understand the logic behind <strong>Container With Most Water</strong> and can solve it efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3423cf9f18f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Celebrity in a Party]]></title>
            <link>https://medium.com/@abhinavcj29/finding-the-celebrity-in-a-party-48735fae82e7?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/48735fae82e7</guid>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[alogrithm]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 07:17:07 GMT</pubDate>
            <atom:updated>2025-08-30T07:17:07.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOwIOJh_vveBsLw9GbmU3Q.png" /></figure><p>Imagine you are at a party where everyone either knows or doesn’t know each other. Among them, there might be a <strong>celebrity</strong> — a person who is known by everyone but does not know anyone in return. How do we find this celebrity efficiently?</p><p>In this post, we’ll break down the problem, understand the logic, and look at an optimized C++ solution.</p><h3>Problem Statement</h3><p>We are given an <strong>n x n matrix</strong> mat, where:</p><ul><li>mat[i][j] = 1 → person i knows person j</li><li>mat[i][j] = 0 → person i does <strong>not</strong> know person j</li></ul><p>We need to find the index of the celebrity. If no celebrity exists, return -1.</p><p><strong>Celebrity rules:</strong></p><ol><li>A celebrity does not know anyone → their <strong>row</strong> should be all 0s.</li><li>Everyone knows the celebrity → their <strong>column</strong> should be all 1s (except the diagonal).</li></ol><h3>Naive Approach</h3><p>We could:</p><ul><li>Check each person’s row to see if they know nobody.</li><li>Then check their column to see if everyone knows them.</li></ul><p>But this would take <strong>O(n²)</strong> time, which is not efficient for large n.</p><h3>Optimized Approach (Two Pointers)</h3><p>We can use the following logic:</p><p>Start with two pointers:</p><ul><li>top = 0</li><li>down = n-1</li></ul><p>While top &lt; down:</p><ul><li>If mat[top][down] == 1, then top knows down → top can’t be celebrity → increment top.</li><li>Else if mat[down][top] == 1, then down knows top → down can’t be celebrity → decrement down.</li><li>Otherwise, eliminate both as no one knows each other so none of them can’t be celebrity either way.</li></ul><p>At the end, we’ll have one <strong>candidate celebrity</strong>.</p><p>Verify the candidate:</p><ul><li>Candidate’s row should be all 0s.</li><li>Candidate’s column should be all 1s (except self).</li></ul><p>If both conditions are true → return index, else -1.</p><p>This approach works in <strong>O(n)</strong> time and <strong>O(1)</strong> extra space.</p><h3>C++ Implementation</h3><pre>class Solution {<br>  public:<br>    int celebrity(vector&lt;vector&lt;int&gt;&gt;&amp; mat) {<br>        int top = 0;<br>        int down = mat[0].size() - 1;<br>        <br>        // Step 1: Find candidate<br>        while(top &lt; down){<br>            if(mat[top][down] == 1){<br>                top++;<br>            }<br>            else if(mat[down][top] == 1){<br>                down--;<br>            }<br>            else{<br>                top++;<br>                down--;<br>            }<br>        }<br>        <br>        if(top &gt; down){<br>            return -1;<br>        }<br>        <br>        // Step 2: Verify candidate<br>        for(int i = 0; i &lt; mat[0].size(); i++){<br>            if(top == i) continue;<br>            if(mat[top][i] == 0 &amp;&amp; mat[i][top] == 1) continue;<br>            else return -1;<br>        }<br>        return top;<br>    }<br>};</pre><h3>Example Walkthrough</h3><p>Input:</p><pre>mat = [ [0, 1, 0],<br>        [0, 0, 0],<br>        [0, 1, 0] ]</pre><ul><li>Person 0 knows 1 → not celebrity.</li><li>Person 2 knows 1 → not celebrity.</li><li>Person 1 knows nobody, and everyone knows 1 → celebrity is <strong>1</strong>.</li></ul><p>Output:</p><pre>1</pre><h3>Complexity Analysis</h3><ul><li><strong>Time Complexity</strong>: O(n) → we eliminate one person in each step and then verify.</li><li><strong>Space Complexity</strong>: O(1) → only pointers are used.</li></ul><h3>Conclusion</h3><p>The celebrity problem is a great example of using elimination and verification to reduce complexity from O(n²) to O(n). The two-pointer technique ensures that we only need one pass to find the candidate and one pass to verify.</p><p>This technique is often used in interview problems because it shows optimization skills beyond brute force.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48735fae82e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smallest Window Substring]]></title>
            <link>https://medium.com/@abhinavcj29/smallest-window-substring-a1ecec347c19?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ecec347c19</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 15:33:14 GMT</pubDate>
            <atom:updated>2025-08-29T15:33:34.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xu0p9QsUK3I-mLkRT11XCg.png" /></figure><p>We are given two strings s and p. The task is to find the <strong>smallest substring in s</strong> which contains <strong>all characters of p (including duplicates)</strong>. If multiple substrings of the same length exist, return the one with the smallest starting index. If no such substring exists, return an empty string.</p><h3>Example</h3><pre>s = &quot;ADOBECODEBANC&quot;<br>p = &quot;ABC&quot;<br>Output = &quot;BANC&quot;</pre><p>Explanation: The substring “BANC” is the smallest substring in s that contains A, B, and C.</p><h3>Approach</h3><p>This problem is a classic <strong>sliding window</strong> problem. The idea is to expand and shrink a window over the string s while ensuring it contains all characters of p.</p><h4>Step 1: Count Required Characters</h4><ul><li>Create a frequency map for all characters in p.</li><li>Example: if p = “AABC”, then:</li></ul><pre>need = { &#39;A&#39;: 2, &#39;B&#39;: 1, &#39;C&#39;: 1 }</pre><h4>Step 2: Expand the Window (Right Pointer)</h4><ul><li>Iterate over s using a right pointer.</li><li>For each character s[right], decrease its frequency in the need map.</li><li>If after decrementing, need[s[right]] &gt;= 0, it means this occurrence was required. Increase a counter “cnt” that tracks how many characters of p are currently matched.</li></ul><h4>Step 3: Shrink the Window (Left Pointer)</h4><ul><li>Whenever cnt == p.size() (all characters matched), try shrinking the window from the left (l) to minimize it.</li><li>While shrinking:</li></ul><p>If the current window is smaller than the previous best, update the answer.</p><p>Increase need[s[l]]++ (since we are removing this character from the window).</p><p>If need[s[l]] &gt; 0, it means we removed a required character, so decrement cnt.</p><p>Move l forward.</p><h4>Step 4: Return Result</h4><ul><li>After traversing the string, if we found a valid window, return it.</li><li>Otherwise, return an empty string.</li></ul><h3>Corrected C++ Code</h3><pre>class Solution {<br>  public:<br>    string smallestWindow(string &amp;s, string &amp;p) {<br>        unordered_map&lt;char,int&gt; need;<br>        for(char c : p){<br>            need[c]++;<br>        }<br>        <br>        int l = 0, r = 0;<br>        int minLen = INT_MAX;<br>        int cnt = 0;<br>        int sIndex = -1;<br>        <br>        while(r &lt; s.size()){<br>            need[s[r]]--;<br>            if(need[s[r]] &gt;= 0){<br>                cnt++;  // this char contributed to p<br>            }<br>            <br>            // try to shrink<br>            while(cnt == p.size()){<br>                if(r - l + 1 &lt; minLen){<br>                    minLen = r - l + 1;<br>                    sIndex = l;<br>                }<br>                need[s[l]]++;   // restore requirement<br>                if(need[s[l]] &gt; 0){<br>                    cnt--;  // lost a required char<br>                }<br>                l++;<br>            }<br>            r++;<br>        }<br>        <br>        return minLen == INT_MAX ? &quot;&quot; : s.substr(sIndex,minLen);<br>    }<br>};</pre><h3>Dry Run Example</h3><p>s = “ADOBECODEBANC”, p = “ABC”</p><ol><li>Initialize need = {A:1, B:1, C:1}</li><li>Expand right until window covers A, B, C → first valid window = ADOBEC.</li><li>Shrink from left → DOBEC → still valid. → OBEC → still valid. → BEC → still valid (size 3).</li><li>Continue expanding/shrinking → eventually find BANC (size 4).</li><li>Final answer = BANC.</li></ol><h3>Complexity</h3><ul><li><strong>Time Complexity:</strong> O(|s| + |p|) (each char processed at most twice).</li><li><strong>Space Complexity:</strong> O(1) (map of fixed character set).</li></ul><h3>Key Takeaway</h3><p>The tricky part is handling the need map correctly:</p><ul><li>Expand → need[s[r]] —</li><li>Shrink → need[s[l]]++</li></ul><p>If you mistakenly decrement on both sides, the logic breaks. The symmetry of increment/decrement ensures correct tracking.</p><p>✅ With sliding window, this problem becomes efficient and elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ecec347c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximum Consecutive 1s with At Most K Flips]]></title>
            <link>https://medium.com/@abhinavcj29/maximum-consecutive-1s-with-at-most-k-flips-ad126432cf38?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad126432cf38</guid>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 15:37:28 GMT</pubDate>
            <atom:updated>2025-08-29T15:34:06.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynvguNvmOOPUIK_RQvf2_w.png" /></figure><p>We are given a binary array arr[] containing only 0s and 1s, and an integer k. We are allowed to flip at most k zeros to ones. The task is to find the maximum number of consecutive 1s that can be obtained in the array after performing at most k flips.</p><h3>Problem Explanation</h3><ul><li><strong>Input:</strong> A binary array and an integer k.</li><li>Example: arr = [1, 0, 1], k = 1</li><li><strong>Output:</strong> The length of the longest consecutive sequence of 1s achievable by flipping at most k zeros.</li><li>Example Output: 3</li></ul><p><strong>Key Idea:</strong> We want the longest subarray that contains at most k zeros (since we can flip them to ones).</p><h3>Logic Used (Sliding Window / Two-Pointer)</h3><p>We use the <strong>sliding window</strong> approach to efficiently find the answer in linear time.</p><p>Maintain a window [l..r] with two pointers: l (left) and r (right).</p><p>Expand r step by step:</p><ul><li>If arr[r] == 0, increment zeros.</li></ul><p>If the number of zeros in the window exceeds k, shrink the window from the left (l++) until zeros &lt;= k again.</p><p>At every step, if the window is valid (zeros &lt;= k), update the maximum length as:</p><pre>maxLen = max(maxLen, r - l + 1)</pre><p>Continue until r reaches the end of the array.</p><p>This way, the window always represents the longest valid subarray ending at r.</p><h3>C++ Implementation</h3><pre><br>    int maxOnes(vector&lt;int&gt;&amp; arr, int k) {<br>        int n = arr.size();<br>        int zeros = 0;<br>        int maxLen = 0;<br>        int l = 0;<br>        int r = 0;<br>        <br>        while (r &lt; n) {<br>            if (arr[r] == 0) {<br>                zeros++;<br>            }<br>            <br>            // shrink window if too many zeros<br>            if (zeros &gt; k) {<br>                if (arr[l] == 0) {<br>                    zeros--;<br>                }<br>                l++;<br>            }<br>            <br>            // update maximum length<br>            if (zeros &lt;= k) {<br>                int len = r - l + 1;<br>                maxLen = max(maxLen, len);<br>            }<br>            r++;<br>        }<br>        return maxLen;<br>    }</pre><h3>Example Dry Run</h3><p>Input:</p><pre>arr = [1, 0, 1], k = 1</pre><h3>Complexity Analysis</h3><p><strong>Time Complexity:</strong> O(n)</p><ul><li>Each element is processed at most twice (once when added to the window, once when removed).</li></ul><p><strong>Space Complexity:</strong> O(1)</p><ul><li>Only a few variables are used.</li></ul><h3>Conclusion</h3><p>This problem is a classic use case for the <strong>sliding window</strong> technique. Instead of checking all possible subarrays (which would be O(n²)), we maintain a dynamic window that always ensures at most k zeros are inside. This reduces the solution to linear time and makes it efficient even for large input sizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad126432cf38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Number of Possible Triangles from an Array]]></title>
            <link>https://medium.com/@abhinavcj29/finding-the-number-of-possible-triangles-from-an-array-7ca250d752d9?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ca250d752d9</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[alogrithm]]></category>
            <category><![CDATA[gfg]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 13:17:51 GMT</pubDate>
            <atom:updated>2025-08-27T13:17:51.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtpfJNZtCvmgipNbU1YV3w.png" /><figcaption>DSA</figcaption></figure><p>When given an integer array arr[], we want to find the number of triangles that can be formed using three different elements of the array as the sides of a triangle.</p><p>A triangle is valid only if the <strong>sum of any two sides is strictly greater than the third side</strong>.</p><h3>Problem Explanation</h3><ul><li><strong>Input:</strong> An integer array, e.g., arr = {4, 6, 3, 7}</li><li><strong>Output:</strong> The number of valid triangles that can be formed.</li></ul><p><strong>Key property:</strong> For sides a, b, c to form a valid triangle:</p><pre>a + b &gt; c<br>b + c &gt; a<br>c + a &gt; b</pre><p>If the array is sorted (a ≤ b ≤ c), only one condition needs to be checked:</p><pre>a + b &gt; c</pre><h3>Approaches</h3><h3>1. Brute Force (O(n³))</h3><p>Check all triplets (i, j, k) and verify the triangle inequality.</p><pre>int countTriangles(vector&lt;int&gt; &amp;arr) {<br>    int n = arr.size(), count = 0;<br>    for (int i = 0; i &lt; n-2; i++) {<br>        for (int j = i+1; j &lt; n-1; j++) {<br>            for (int k = j+1; k &lt; n; k++) {<br>                int a = arr[i], b = arr[j], c = arr[k];<br>                if (a + b &gt; c &amp;&amp; a + c &gt; b &amp;&amp; b + c &gt; a)<br>                    count++;<br>            }<br>        }<br>    }<br>    return count;<br>}</pre><h3>2. Optimized Two-Pointer Approach (O(n²))</h3><p><strong>Sort the array</strong> in non-decreasing order.</p><ul><li>Sorting makes it easier to apply the triangle inequality rule.</li></ul><p><strong>Pick the largest side first</strong> (say arr[k]).</p><ul><li>Then we need to find two smaller sides arr[i] and arr[j] such that:</li><li>arr[i] + arr[j] &gt; arr[k].</li></ul><p><strong>Use two-pointer approach</strong> for each k:</p><ul><li>Initialize two indices: i = 0 (smallest side), j = k-1 (second largest side).</li><li>While i &lt; j:</li><li>If arr[i] + arr[j] &gt; arr[k] → then all pairs between i and j with j fixed will form valid triangles (because array is sorted, so arr[i+1] + arr[j], arr[i+2] + arr[j], … will also be greater than arr[k]).</li><li>So, add (j — i) to the count, and move j — .</li><li>Else (arr[i] + arr[j] &lt;= arr[k]) → move i++ (to increase the sum).</li></ul><p><strong>Repeat</strong> for all k from last index down to 2.</p><p>The final count is the total number of possible triangles.</p><pre>int countTriangles(vector&lt;int&gt; &amp;arr) {<br>    int n = arr.size();<br>    sort(arr.begin(), arr.end());<br>    int count = 0;<br><br>    for (int k = n-1; k &gt;= 2; k--) {<br>        int i = 0, j = k-1;<br>        while (i &lt; j) {<br>            if (arr[i] + arr[j] &gt; arr[k]) {<br>                count += (j - i);<br>                j--;<br>            } else {<br>                i++;<br>            }<br>        }<br>    }<br>    return count;<br>}</pre><h3>Example Dry Run</h3><p>Input:</p><pre>arr = {4, 6, 3, 7}</pre><p>Step 1: Sort → {3, 4, 6, 7}</p><p>Fix k=3 (largest side = 7)</p><ul><li>i=0 (3), j=2 (6) → 3+6=9 &gt; 7 ✅ → add 2 triangles: (3,6,7), (4,6,7)</li><li>count = 2</li></ul><p>Fix k=2 (largest side = 6)</p><ul><li>i=0 (3), j=1 (4) → 3+4=7 &gt; 6 ✅ → add 1 triangle: (3,4,6)</li><li>count = 3</li></ul><p>Total = 3 triangles.</p><p>Output:</p><pre>3</pre><h3>Complexity Analysis</h3><p><strong>Brute Force (O(n³))</strong></p><ul><li>Three nested loops, check every triplet.</li><li>Not feasible for large n (&gt;1000).</li></ul><p><strong>Optimized (O(n²))</strong></p><ul><li>Sorting: O(n log n)</li><li>Two-pointer scanning: O(n²)</li><li>Much faster and works for large input sizes</li></ul><h3>Conclusion</h3><ul><li>Brute force is simple but slow.</li><li>The optimized two-pointer approach reduces complexity to O(n²).</li><li>Sorting the array helps simplify the triangle inequality check to a single condition.</li></ul><p><strong>Final takeaway:</strong> Always sort first, then use the largest side with a two-pointer strategy for efficient triangle counting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ca250d752d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is One String a Subsequence of Another?]]></title>
            <link>https://medium.com/@abhinavcj29/is-one-string-a-subsequence-of-another-7813f7b1b9c6?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/7813f7b1b9c6</guid>
            <category><![CDATA[gfg]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 16:24:48 GMT</pubDate>
            <atom:updated>2025-08-26T16:41:56.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*npvdGpE4I4ImzBi6J31AuQ@2x.jpeg" /></figure><p>We are given two strings s1 and s2. We need to check whether s1 is a <strong>subsequence</strong> of s2 or not.</p><p>A <strong>subsequence</strong> of a string is a new string generated by deleting some characters (possibly none) from the original string, without changing the order of the remaining characters.</p><p><strong>Example:</strong></p><ul><li>“abc” is a subsequence of “aebdc”.</li><li>“axc” is <strong>not</strong> a subsequence of “ahbgdc”.</li></ul><h3>Explanation</h3><p>We need to verify whether all characters of s1 appear in s2 <strong>in the same relative order</strong>, but they do not have to be contiguous.</p><p>The idea is simple:</p><ul><li>Use two pointers, one for each string.</li><li>Traverse s2 (the bigger string).</li><li>If the current character of s2 matches the current character of s1, move the pointer on s1.</li><li>At the end, if we have matched all characters of s1, then it’s a subsequence.</li></ul><p>This works in <strong>O(|s2|)</strong> time and uses <strong>O(1)</strong> extra space.</p><h3>Example</h3><p><strong>Input:</strong></p><p>s1 = “abc”</p><p>s2 = “aebdc”</p><p><strong>Steps:</strong></p><ul><li>Compare ‘a’ (s1[0]) with ‘a’ (s2[0]) → match → move i</li><li>Compare ‘b’ (s1[1]) with ‘e’ (s2[1]) → not match → move j</li><li>Compare ‘b’ (s1[1]) with ‘b’ (s2[2]) → match → move i</li><li>Compare ‘c’ (s1[2]) with ‘d’ (s2[3]) → not match → move j</li><li>Compare ‘c’ (s1[2]) with ‘c’ (s2[4]) → match → move i</li></ul><p>Now i == s1.size(), so “abc” <strong>is</strong> a subsequence of “aebdc”</p><h3>C++ Code</h3><pre>#include &lt;bits/stdc++.h&gt;<br>using namespace std;<br><br>class Solution {<br>public:<br>    bool isSubSeq(string&amp; s1, string&amp; s2) {<br>        int i = 0;<br>        for (char c : s2) {<br>            if (i &lt; s1.size() &amp;&amp; c == s1[i]) {<br>                i++;<br>                if (i == s1.size()) return true; // early exit<br>            }<br>        }<br>        return (i == s1.size());<br>    }<br>};<br><br>int main() {<br>    Solution sol;<br>    string s1 = &quot;abc&quot;, s2 = &quot;aebdc&quot;;<br>    if (sol.isSubSeq(s1, s2))<br>        cout &lt;&lt; s1 &lt;&lt; &quot; is a subsequence of &quot; &lt;&lt; s2 &lt;&lt; endl;<br>    else<br>        cout &lt;&lt; s1 &lt;&lt; &quot; is NOT a subsequence of &quot; &lt;&lt; s2 &lt;&lt; endl;<br>}</pre><h3>Code Explanation</h3><ul><li>int i = 0; → pointer for s1.</li><li>Loop through each character c in s2.</li><li>If c == s1[i], we increment i.</li><li>If i reaches s1.size(), that means we have successfully matched the entire s1 inside s2.</li><li>Finally, return whether i == s1.size().</li></ul><h3>Dry Run</h3><p>Input:</p><p>s1 = “abc”, s2 = “aebdc”</p><p>Input:</p><p>s1 = “abc”, s2 = “aebdc”</p><p>Start with i = 0.</p><ul><li>Compare s1[0] = ‘a’ with s2[0] = ‘a’.</li><li>Match → move i to 1.</li></ul><p>Now i = 1.</p><ul><li>Compare s1[1] = ‘b’ with s2[1] = ‘e’.</li><li>Not a match → move in s2.</li></ul><p>Still i = 1.</p><ul><li>Compare s1[1] = ‘b’ with s2[2] = ‘b’.</li><li>Match → move i to 2.</li></ul><p>Now i = 2.</p><ul><li>Compare s1[2] = ‘c’ with s2[3] = ‘d’.</li><li>Not a match → move in s2.</li></ul><p>Still i = 2.</p><ul><li>Compare s1[2] = ‘c’ with s2[4] = ‘c’.</li><li>Match → move i to 3.</li></ul><p>Since i == s1.size(), we matched all characters of s1 inside s2.</p><p>“abc” is a subsequence of “aebdc”.</p><p>That’s how we check if one string is a subsequence of another!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7813f7b1b9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Farthest Smaller Element in an Array]]></title>
            <link>https://medium.com/@abhinavcj29/finding-the-farthest-smaller-element-in-an-array-d552bc163cc7?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/d552bc163cc7</guid>
            <category><![CDATA[gfg]]></category>
            <category><![CDATA[alogrithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 12:15:57 GMT</pubDate>
            <atom:updated>2025-08-19T12:42:04.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8ul-op3IeEx3cYt_5oazw.png" /></figure><p>You are given an array arr[] of size n. For each element arr[i], the task is to find the farthest index j such that:</p><ul><li>j &gt; i</li><li>arr[j] &lt; arr[i]</li></ul><p>If no such index exists, return -1 for that element.</p><p>The output should be an array of size n where each element stores the farthest index satisfying the above condition.</p><h3>Example</h3><p><strong>Input:</strong></p><p>arr = [2, 5, 1, 3, 2]</p><p><strong>Output:</strong></p><p>[2, 4, -1, 4, -1]</p><p><strong>Explanation:</strong></p><ul><li>For arr[0] = 2, the farthest index where element is smaller is at j = 2 (arr[2] = 1).</li><li>For arr[1] = 5, the farthest smaller is at j = 4 (arr[4] = 2).</li><li>For arr[2] = 1, no element on the right is smaller.</li><li>For arr[3] = 3, no element on the right is smaller.</li><li>For arr[4] = 2, no element on the right is smaller.</li></ul><h3>Naive Approach (O(n²))</h3><p>For every element arr[i], scan all indices j where j &gt; i and check if arr[j] &lt; arr[i].</p><ul><li>Keep track of the farthest such index.</li><li>If none found, assign -1.</li></ul><p>While easy to implement, this solution is inefficient for large arrays.</p><h3>Optimized Approach (O(n log n))</h3><p>We can do better using:</p><p><strong>Suffix Minimum Array (Step 1)</strong></p><ul><li>Construct an array suff[] where suff[i] stores the minimum value from arr[i] to arr[n-1].</li><li>This allows us to quickly check if there exists a smaller element at or after index i.</li></ul><p><strong>Binary Search (Step 2)</strong></p><ul><li>For each arr[i], perform binary search on the suff[] array in the range [i+1, n-1].</li><li>Find the farthest index j such that suff[j] &lt; arr[i].</li></ul><h3>Implementation in C++</h3><pre>class Solution {<br>  public:<br>   vector&lt;int&gt; farMin(vector&lt;int&gt;&amp; arr) {<br>        int n = arr.size();<br>        vector&lt;int&gt; ans(n, -1);<br>        vector&lt;int&gt; suff(n);<br>        <br>        // Build suffix minimum array<br>        suff[n-1] = arr[n-1];<br>        for(int i = n - 2; i &gt;= 0; i--){<br>            suff[i] = min(arr[i], suff[i+1]);<br>        }<br>        <br>        // For each element, binary search on suffix<br>        for(int i = 0; i &lt; n; i++){<br>            int s = i+1;<br>            int e = n-1;<br>            int res = -1;<br>            <br>            while(s &lt;= e){<br>                int mid = (s+e) / 2;<br>                if(suff[mid] &lt; arr[i]){<br>                    res = mid;   // valid candidate, try to go farther<br>                    s = mid + 1;<br>                } else {<br>                    e = mid - 1;<br>                }<br>            }<br>            ans[i] = res;<br>        }<br>        return ans;<br>    }<br>};</pre><h3>Dry Run Example</h3><p><strong>Input:</strong> arr = [2, 5, 1, 3, 2]</p><p>Step 1: Build suffix min array</p><p>suff[4] = 2<br>suff[3] = min(3, 2) = 2<br>suff[2] = min(1, 2) = 1<br>suff[1] = min(5, 1) = 1<br>suff[0] = min(2, 1) = 1</p><p>So, suff = [1, 1, 1, 2, 2]</p><p>Step 2: Binary Search for Each Index</p><p>Now for each i, binary search in [i+1..n-1] on suff[] to find farthest position where suff[mid] &lt; arr[i].</p><h4>i = 0, arr[0] = 2</h4><p>Search range [1..4] in suff = [1, 1, 1, 2, 2]</p><ul><li>suff[1] = 1 &lt; 2 → candidate res=1 → move right</li><li>suff[2] = 1 &lt; 2 → candidate res=2 → move right</li><li>suff[3] = 2 !&lt; 2 → move left</li><li>suff[2] checked already → stop</li></ul><p>Farthest j = <strong>2</strong></p><h4>i = 1, arr[1] = 5</h4><p>Search range [2..4] in suff = [1, 2, 2]</p><ul><li>suff[3] = 2 &lt; 5 → res=3 → move right</li><li>suff[4] = 2 &lt; 5 → res=4 → move right</li><li>stop</li></ul><p>Farthest j = <strong>4</strong></p><h4>i = 2, arr[2] = 1</h4><p>Search range [3..4] in suff = [2, 2]</p><ul><li>suff[3] = 2 !&lt; 1 → move left</li><li>suff[4] = 2 !&lt; 1 → move left</li><li>stop</li></ul><p>No valid j → <strong>-1</strong></p><h4>i = 3, arr[3] = 3</h4><p>Search range [4..4] in suff = [2]</p><ul><li>suff[4] = 2 &lt; 3 → res=4</li></ul><p>Farthest j = <strong>4</strong></p><h4>i = 4, arr[4] = 2</h4><p>No elements to the right → <strong>-1</strong></p><h3>Final Answer</h3><p>ans = [2, 4, -1, 4, -1]</p><h3>Time Complexity</h3><ul><li>Building suffix array: O(n)</li><li>Binary search for each element: O(n log n)</li><li>Overall: <strong>O(n log n)</strong></li></ul><p>Space Complexity: O(n) for suffix array and result array.</p><h3>Common Doubts</h3><p><strong>1. Why do we need a suffix minimum array?</strong></p><p>Because it allows us to quickly know the minimum element from index j to the end. Without it, binary search would not be possible.</p><p><strong>2. Why binary search works here?</strong></p><p>The suffix minimum array is <strong>non-increasing</strong>. This monotonic property allows binary search to locate the farthest valid index.</p><p><strong>3. Why do we search for the farthest j, not the nearest?</strong></p><p>The problem statement explicitly asks for the farthest index where the condition holds true.</p><p><strong>4. What if all elements are strictly increasing?</strong></p><p>In that case, every element will get -1 because no element to the right will be smaller.</p><p><strong>5. Can we reduce space further?</strong></p><p>We need the suffix array for binary search, so O(n) space is necessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d552bc163cc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Solving the H-Index Problem in O(n)]]></title>
            <link>https://medium.com/@abhinavcj29/understanding-and-solving-the-h-index-problem-in-o-n-40a176c9e890?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a176c9e890</guid>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[gfg]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 17:56:29 GMT</pubDate>
            <atom:updated>2025-08-18T17:56:29.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpNZsAPBKyXcreSEZ40nnw.png" /></figure><p>The <strong>H-index</strong> is a common metric used in academia to measure both productivity and citation impact of a researcher’s work.</p><p><strong>Definition:</strong></p><p>A researcher has an H-index of H if:</p><ul><li>They have published at least <strong>H papers</strong>, and</li><li>Each of those papers has been cited at least <strong>H times</strong>.</li></ul><h3>Problem Statement</h3><p>You are given an array citations[], where citations[i] represents the number of citations for the i-th paper.</p><p>You need to calculate the researcher’s <strong>H-index</strong>.</p><h3>Example</h3><p>citations = [3, 0, 6, 1, 5]</p><ul><li>Sorted version → [0, 1, 3, 5, 6]</li><li>At least 3 papers ([3,5,6]) have ≥ 3 citations</li><li>No 4 papers have ≥ 4 citations</li><li>So the H-index = <strong>3</strong></li></ul><h3>Efficient O(n) Solution (Bucket Counting)</h3><p>Instead of sorting (O(n log n)), we use <strong>bucket counting</strong>.</p><h3>Idea:</h3><ul><li>Maximum H-index can never exceed n (number of papers).</li><li>Create an array count[0..n]</li><li>If a paper has c citations:</li><li>If c &gt;= n, increment count[n]</li><li>Else increment count[c]</li><li>Traverse backwards from n → 0, maintaining a cumulative sum of papers with ≥ i citations.</li><li>The first i where total ≥ i is the H-index.</li></ul><h3>C++ Implementation</h3><pre>#include &lt;vector&gt;<br>using namespace std;<br><br>int hIndex(vector&lt;int&gt;&amp; citations) {<br>    int n = citations.size();<br>    vector&lt;int&gt; count(n + 1, 0);<br><br>    // Count citations, cap at n<br>    for (int c : citations) {<br>        if (c &gt;= n) count[n]++;<br>        else count[c]++;<br>    }<br><br>    // Traverse backwards<br>    int total = 0;<br>    for (int i = n; i &gt;= 0; i--) {<br>        total += count[i];  // papers with ≥ i citations<br>        if (total &gt;= i) return i;<br>    }<br>    return 0;<br>}</pre><h3>Example Walkthrough</h3><p>For citations = [3,0,6,1,5], n=5:</p><p>count = [1,1,0,1,0,2]</p><p>Checking backwards:</p><ul><li>i=5 → total=2, need ≥5 → ❌</li><li>i=4 → total=2, need ≥4 → ❌</li><li>i=3 → total=3, need ≥3 → ✅ H-index = 3</li></ul><h3>Key Takeaways</h3><ul><li>Sorting-based approach = O(n log n)</li><li>Bucket-based approach = <strong>O(n) time, O(n) space</strong></li><li>Great example of applying counting techniques to avoid sorting.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a176c9e890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sort by Absolute Difference]]></title>
            <link>https://medium.com/@abhinavcj29/sort-by-absolute-difference-a760f2811018?source=rss-5fd6638e4624------2</link>
            <guid isPermaLink="false">https://medium.com/p/a760f2811018</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Abhinav Chauhan]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 18:19:39 GMT</pubDate>
            <atom:updated>2025-08-19T12:58:04.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1tVciALBm8bX4Qbb1NBsg.png" /></figure><p>Sometimes in programming, we need to <strong>rearrange an array based on how “close” its elements are to a given number</strong>. This is a common problem in interviews and real-world scenarios like finding nearest values, ranking, or clustering.</p><p>In this post, we’ll discuss the problem, approach, and C++ solution with explanations.</p><h3>Problem Statement</h3><p>You are given:</p><ul><li>An integer x</li><li>An array arr[] of integers</li></ul><p>Your task is to <strong>rearrange the elements of the array</strong> such that elements with the <strong>smallest absolute difference from x</strong> come first.</p><p><strong>Important:</strong></p><ul><li>If two elements have the <strong>same difference</strong>, they should <strong>remain in their original order</strong>.</li></ul><p><strong>Example:</strong></p><p>Input:<br>x = 5<br>arr = [10, 3, 7, 2, 8]</p><p>Output:<br>[3, 7, 2, 8, 10]</p><p><strong>Explanation:</strong></p><p>| Element | |Difference from 5|</p><p>| — — — | — — — — |</p><p>| 10 | | 5 |</p><p>| 3 | | 2 |</p><p>| 7 | | 2 |</p><p>| 2 | | 3 |</p><p>| 8 | | 3 |</p><ul><li>Elements with <strong>difference 2</strong> → 3, 7 (order preserved)</li><li>Elements with <strong>difference 3</strong> → 2, 8 (order preserved)</li><li>Element with <strong>difference 5</strong> → 10</li></ul><h3>Approach / Logic</h3><p>Here’s the step-by-step approach:</p><p><strong>Calculate Absolute Differences</strong></p><ul><li>For each element in the array, calculate abs(element — x).</li></ul><p><strong>Stable Sorting</strong></p><ul><li>Use a <strong>stable sorting algorithm</strong> to sort the array based on the absolute differences.</li><li>A <strong>stable sort</strong> ensures that if two elements have the same difference, their original relative order is preserved.</li></ul><p><strong>Rearrange the Array</strong></p><ul><li>After sorting, the array will be rearranged in the required order.</li></ul><p><strong>Key Points:</strong></p><ul><li>Absolute difference: abs(a — x)</li><li>Stable sorting is essential to preserve order of equal differences.</li></ul><h3>C++ Solution</h3><p>C++ makes this problem easy using <strong>std::stable_sort</strong> and <strong>lambda functions</strong>.</p><p>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;cmath&gt;</p><p>int main() {<br> int x = 5; // Number to compare<br> std::vector&lt;int&gt; arr = {10, 3, 7, 2, 8};</p><p>// Stable sort based on absolute difference from x<br> std::stable_sort(arr.begin(), arr.end(), [x](int a, int b) {<br> return std::abs(a — x) &lt; std::abs(b — x);<br> });</p><p>// Print the rearranged array<br> for (int num : arr) {<br> std::cout &lt;&lt; num &lt;&lt; “ “;<br> }</p><p>return 0;<br>}</p><p><strong>Output:</strong></p><p>3 7 2 8 10</p><h3>Explanation of the Code</h3><p><strong>std::stable_sort(arr.begin(), arr.end(), lambda)</strong></p><ul><li>Sorts the array in ascending order based on the lambda function.</li><li>“Stable” ensures elements with equal differences keep their <strong>original relative order</strong>.</li></ul><p><strong>Lambda Function [x](int a, int b)</strong></p><ul><li>[x] → captures the value of x from the surrounding scope.</li><li>(int a, int b) → parameters representing two elements being compared.</li><li>return std::abs(a — x) &lt; std::abs(b — x); → returns true if a should come before b based on absolute difference.</li></ul><p><strong>Printing the Result</strong></p><ul><li>After sorting, we simply print the array in its new order.</li></ul><h3>Complexity</h3><ul><li><strong>Time Complexity:</strong> O(n log n) (for sorting)</li><li><strong>Space Complexity:</strong> O(1) extra space if using in-place stable sort</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a760f2811018" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>