<?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 Mehul Jain on Medium]]></title>
        <description><![CDATA[Stories by Mehul Jain on Medium]]></description>
        <link>https://medium.com/@mehuljain.blr?source=rss-ce1d56cb854d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YZEUYJpuEm-2-N3K</url>
            <title>Stories by Mehul Jain on Medium</title>
            <link>https://medium.com/@mehuljain.blr?source=rss-ce1d56cb854d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:46:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehuljain.blr/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[Maximum Subarray Sum]]></title>
            <link>https://medium.com/@mehuljain.blr/maximum-subarray-sum-30197447f8cb?source=rss-ce1d56cb854d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30197447f8cb</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Mehul Jain]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 19:11:36 GMT</pubDate>
            <atom:updated>2026-10-06T18:26:41.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*QC_uMYgqU69rH2J9" /></figure><p>A single problem can often be solved using multiple methods with different space and time complexities. Problems such as finding the sums, maxima, minima, or even binary operations involve iterating over the entire data and optionally using another data structure that is well suited to the problem.</p><p>One such problem is the maximum subarray sum. Think about a game (like <a href="https://supercell.com/en/games/clashroyale/">Clash Royale</a>) where you lose or gain points depending on the outcome of each match you play. A very common feature of such games is to show the best streak you have had along with the range of the best streak.</p><p>You initially start with 0 points, and since you are new to the game, you would naturally lose the first few games. Let’s assume that your first 3 games looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*DMAQLQ_pJvzLVOq4-AihlA.png" /></figure><p>Your best streak among the first 3 games is 5, and that is in your very second game. The range (following 0-indexing) would be [1,1].</p><p>Now that you have figured out the game, you start to win more games than you lose. Let’s assume that the next 5 games look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPNYVmriP_QvNkIQlT10HA.png" /></figure><p>Your streak now becomes 46, i.e., (-3) + (5) + (-1) + (1) + (25) + (19), and that is right from your first game all the way till the sixth game, and your streak range becomes [0,5].</p><p>Now let’s extend this to a larger number of matches, and this is what your entire gameplay looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsAKoHXdWx12IJpZMLwEtw.png" /></figure><p>The final streak is 52 and involves your ninth and tenth games.</p><h3>Code it out!</h3><p>A few variables initialised…</p><pre>a = [1, 25, 19, -22, 15, -3, -53, -1, 2, 50, -1]<br>max_sub, sub_start, sub_stop = float(&#39;-inf&#39;), 0, 0</pre><p>The max_sub variable stores the maximum sum, i.e., the best streak. The [sub_start, sub_stop] are the start and the end of the subarray with the maximum sum, i.e., the start and the end of the streak.</p><h4>Approach 1</h4><p>Let’s iterate over all subarrays and calculate the sum of each.</p><pre>for i in range(len(a)):<br>    for j in range(i, len(a)):<br>        sub_sum = 0<br>        for k in range(i, j + 1):<br>            sub_sum += a[k] # subarray a[i : j + 1]&#39;s sum</pre><p>The sub_sum variable stores the sum of the subarray from index i to j (both included). Every time we calculate the subarray sum, we compare it with the already initialised max_sub.</p><p>If sub_sum &gt; max_sub, we have a new max_sub, i.e., a better streak, and every time we have a new maximum, we update sub_start and sub_stop with the starts and the ends of the sub_sum, i.e., the start and the stop of the streak.</p><pre>for i in range(len(a)):<br>    for j in range(i, len(a)):<br>        sub_sum = 0<br>        for k in range(i, j + 1):<br>            sub_sum += a[k]<br>        if max_sub &lt; sub_sum: # found a better streak!<br>            max_sub = sub_sum # update the max_sub with the better streak<br>            sub_start = i # start of the better streak<br>            sub_stop = j # end of the better streak</pre><p>The time complexity of the above method is O(n³), as we iterate through the entire array to generate all sub-arrays (i.e., O(n²)) and then compute the sum of each sub-array (i.e., O (n²)), yielding O(n² x n) = O(n³).</p><p>The space complexity is the same as the input’s space complexity, i.e., O(n), since we are doing all of this in place. The solution alone is a constant space, i.e., an O(1) solution.</p><h4>Approach 2</h4><p>Now, we have a method to get the subarray using just two loops where the end of the subarray (j) always moves ahead by 1, away from the start of the subarray (i).</p><pre>for i in range(len(a)):<br>    for j in range(i, len(a)):<br>        # subarray is basically a[i : j + 1]</pre><p>The index j is moving by one each time. This means that as j moves, it is already visiting every element of the current subarray. So instead of using another loop to go through the subarray and calculate its sum, we can simply keep adding a[j] to sub_sum.</p><pre>for i in range(len(a)):<br>    sub_sum = 0<br>    for j in range(i, len(a)):<br>        sub_sum += a[j]</pre><p>The sub_sum now stores the sum of the subarray. Every time we have a new sub_array, we need to do exactly what we were doing before:</p><ol><li>Check if sub_sum is greater than max_sum.</li><li>If yes, we update max_sum with sub_sum and then update the start and end of the subarray with the indices of that subarray with the new maximum sub_sum.</li></ol><pre>for i in range(len(a)):<br>    sub_sum = 0<br>    for j in range(i, len(a)):<br>        sub_sum += a[j] # Getting the sum of the sub-array a(i,j) by moving j<br>        if max_sub &lt; sub_sum: # found a better streak!<br>            max_sub = sub_sum # update the max_sub with the better streak<br>            sub_start = i # start of the better streak<br>            sub_stop = j # end of the better streak</pre><p>The time complexity of the above method is now O(n²) as we iterate through the entire array to get all subarrays and find the sum as and when our subarray size changes by 1.</p><p>The space complexity is still the same as O(n) (or O(1) if we exclude the input’s space complexity).</p><h4>Approach 3</h4><p>Can we drop the inner loop? Let’s consider two scenarios.</p><p>In the first scenario, calculate the sub_sum by iterating through the array; when we come across an element that helps continue the sub_sum, we include it.</p><pre>sub_sum, max_start = 0, 0<br>for i in range(len(a)):<br>    if a[i] &lt; a[i] + sub_sum:<br>        sub_sum += a[i]</pre><p>The second scenario is when we say that it is better to start from the current element and drop the previous elements, and hence discard sub_sum (i.e., sub_sum is negative). We update the sub_start to start from the current index.</p><pre>for i in range(len(a)):<br>    if a[i] &lt; a[i] + sub_sum:<br>        sub_sum += a[i]<br>    else:<br>        sub_sum = a[i]<br>        sub_start = i</pre><p>We still need to keep track of the best subarray we’ve seen so far. So, after calculating the sub_sum, we compare it with max_sub and update it if we&#39;ve found a better one.</p><pre>for i in range(len(a)):<br>    if a[i] &lt; a[i] + sub_sum:<br>        sub_sum += a[i]<br>    else:<br>        sub_sum = a[i]<br>        sub_start = i # start of the better streak<br>    if max_sub &lt; sub_sum:<br>        max_sub = sub_sum # update the max_sub with the better streak<br>        max_start = sub_start # update start of currently best subarray<br>        sub_stop = i # end of the better streak</pre><p>This is a famous algorithm called <strong>Kadane’s Algorithm</strong>.</p><p>The time complexity of the above method is O(n), as we iterate through the entire array once to compute the maximum subarray sum, and the space complexity is the same as in the previous approaches.</p><h3>Compare it!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5U--A6TUbiD_VqFCEFeFw.png" /></figure><p>The time taken to execute varies with different approaches as expected. Here is another table from CSES’s “Maximum subarray sum” section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*z54_2xBzNFKgCfNgBpZ3vQ.png" /></figure><p>NOTE: Comparing times between the two would not be accurate as the execution environment is different for both. What is more indicative is how the time rises with the size of the array across approaches.</p><h4>Full Code</h4><pre>a = [1, 25, 19, -22, 501, -3, -53, -1, 2, 50, -1]<br><br># Approach 1<br>max_sub, sub_start, sub_stop = float(&#39;-inf&#39;), 0, 0<br><br>for i in range(len(a)):<br>    for j in range(i, len(a)):<br>        sub_sum = 0<br>        for k in range(i, j + 1):<br>            sub_sum += a[k]<br>        if max_sub &lt; sub_sum: # found a better streak!<br>            max_sub = sub_sum # update the max_sub with the better streak<br>            sub_start = i # start of the better streak<br>            sub_stop = j # end of the better streak<br><br>print(max_sub, sub_start, sub_stop)<br><br># Approach 2<br>max_sub, sub_start, sub_stop = float(&#39;-inf&#39;), 0, 0<br><br>for i in range(len(a)):<br>    sub_sum = 0<br>    for j in range(i, len(a)):<br>        sub_sum += a[j]<br>        if max_sub &lt; sub_sum: # found a better streak!<br>            max_sub = sub_sum # update the max_sub with the better streak<br>            sub_start = i # start of the better streak<br>            sub_stop = j # end of the better streak<br><br>print(max_sub, sub_start, sub_stop)<br><br># Approach 3<br>max_sub, sub_start, sub_stop = float(&#39;-inf&#39;), 0, 0<br><br>sub_sum, max_start = 0, 0<br>for i in range(len(a)):<br>    if a[i] &lt; a[i] + sub_sum:<br>        sub_sum += a[i]<br>    else:<br>        sub_sum = a[i]<br>        sub_start = i<br>    if max_sub &lt; sub_sum:<br>        max_sub = sub_sum # update the max_sub with the better streak<br>        max_start = sub_start # update the start of the currently best subarray<br>        sub_stop = i # end of the better streak<br><br>print(max_sub, max_start, sub_stop)</pre><h3>Grind?</h3><ol><li><a href="https://leetcode.com/problems/maximum-subarray/description/">LeetCode — Maximum Subarray</a></li><li><a href="https://cses.fi/problemset/task/1643">CSES — Maximum Subarray Sum</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30197447f8cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segment Tree]]></title>
            <link>https://medium.com/@mehuljain.blr/segment-tree-1473ad2d52b8?source=rss-ce1d56cb854d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1473ad2d52b8</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Mehul Jain]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 18:45:58 GMT</pubDate>
            <atom:updated>2026-08-20T09:50:42.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*oowOf06OOPF49V3uJiWwvg.jpeg" /></figure><h3>What is a segment tree?</h3><p>Consider two operations: updating an array element AND finding the answer for a request in a particular range.</p><p>Updating the value of an array is generally a constant-time operation — O(1). But calculating the sum or even the maximum/minimum in a range would be a linear-time operation — O(N).</p><p>Now imagine Spotify maintaining a “Top Songs” chart for a genre, where the chart is really just the maximum stream count among all songs in that genre. A song suddenly goes viral — its stream count updates every second as millions of people hit play. Each of those updates is fast on its own, just one number changing. But to keep the top chart accurate, you’d need to rescan every song in the genre after <em>every single stream</em> to check if the maximum changed. With thousands of songs in a genre and updates happening constantly, that’s an enormous amount of repeated work just to answer the same question — “what’s the max?” — over and over again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1473ad2d52b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R’s complement]]></title>
            <link>https://medium.com/@mehuljain.blr/rs-complement-a297f50e3f6a?source=rss-ce1d56cb854d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a297f50e3f6a</guid>
            <dc:creator><![CDATA[Mehul Jain]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 19:04:51 GMT</pubDate>
            <atom:updated>2026-08-11T19:04:51.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*QYBmCB_II56yAPG8BLvy9w.jpeg" /></figure><h3>What is R’s complement?</h3><p>R’s complement (also called radix complement) is a way of representing numbers in a given base (radix) R.</p><h3>How is R’s complement calculated?</h3><p>The R’s complement for a d-digit number, X, is given by <strong>Rᵈ — X</strong></p><h3>Points to keep in mind…</h3><ul><li><em>The number of digits in X and its R’s complement should be equal to d.</em></li><li><em>The number should always be padded with zeros to make it a d-digit R’s complement.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a297f50e3f6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Depth Matters!]]></title>
            <link>https://medium.com/@mehuljain.blr/depth-matters-403a0c7984dc?source=rss-ce1d56cb854d------2</link>
            <guid isPermaLink="false">https://medium.com/p/403a0c7984dc</guid>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Mehul Jain]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 18:20:03 GMT</pubDate>
            <atom:updated>2026-10-16T17:58:50.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*QYBmCB_II56yAPG8BLvy9w.jpeg" /></figure><h3>Computer Science</h3><h4>Data Structures &amp; Algorithms</h4><p><strong><em>Time Complexity</em></strong></p><ul><li><a href="https://medium.com/@mehuljain.blr/maximum-subarray-sum-30197447f8cb?sharedUserId=mehuljain.blr">Maximum Subarray Sum</a></li></ul><p><strong><em>Sorting</em></strong></p><p><strong><em>Data Structures</em></strong></p><p><strong><em>Complete Search</em></strong></p><p><strong><em>Greedy Algorithms</em></strong></p><p><strong><em>Dynamic Programming</em></strong></p><p><strong><em>Amortized Analysis</em></strong></p><p><strong><em>Range Queries</em></strong></p><p><strong><em>Bit Manipulation</em></strong></p><p><strong><em>Basics of Graphs</em></strong></p><p><strong><em>Graph Traversal</em></strong></p><p><strong><em>Shortest Paths</em></strong></p><p><strong><em>Tree Algorithms</em></strong></p><p><strong><em>Spanning Trees</em></strong></p><p><strong><em>Directed Graphs</em></strong></p><p><strong><em>Strong Connectivity</em></strong></p><p><strong><em>Tree Queries</em></strong></p><p><strong><em>Paths &amp; Circuits</em></strong></p><p><strong><em>Flows &amp; Cuts</em></strong></p><p><strong><em>Number Theory</em></strong></p><p><strong><em>Combinatorics</em></strong></p><p><strong><em>Matrices</em></strong></p><p><strong><em>Probability</em></strong></p><p><strong><em>Game Theory</em></strong></p><p><strong><em>String Algorithms</em></strong></p><p><strong><em>Square Root Algorithms</em></strong></p><p><strong><em>Geometry</em></strong></p><p><strong><em>Sweep Line Algorithms</em></strong></p><h3>Data Science</h3><h4>Mathematics</h4><p><strong><em>Linear algebra</em></strong></p><p><strong><em>Analytic Geometry</em></strong></p><p><strong><em>Matrix Decompositions</em></strong></p><p><strong><em>Vector Calculus</em></strong></p><p><strong><em>Probability and Distributions</em></strong></p><p><strong><em>Continuous Optimization</em></strong></p><p><strong><em>When Models Meet Data</em></strong></p><p><strong><em>Linear Regression</em></strong></p><p><strong><em>Dimensionality Reduction with Principal Component Analysis</em></strong></p><p><strong><em>Density Estimation with Gaussian Mixture Models</em></strong></p><p><strong><em>Classification with Support Vector Machines</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=403a0c7984dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>