<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Aanjaney’s Substack]]></title><description><![CDATA[Explore the magic of Math and CS! Join me for captivating insights at the intersection of mathematics and computer science. Subscribe now for a journey into elegant algorithms and their real-world applications.]]></description><link>https://aanjaneykumarverma.substack.com</link><image><url>https://substackcdn.com/image/fetch/$s_!tOqB!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F16b7d0c8-9b78-4820-9449-b307ed2d5430_220x220.png</url><title>Aanjaney’s Substack</title><link>https://aanjaneykumarverma.substack.com</link></image><generator>Substack</generator><lastBuildDate>Tue, 12 May 2026 03:48:58 GMT</lastBuildDate><atom:link href="https://aanjaneykumarverma.substack.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Aanjaney]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[aanjaneykumarverma@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[aanjaneykumarverma@substack.com]]></itunes:email><itunes:name><![CDATA[Aanjaney]]></itunes:name></itunes:owner><itunes:author><![CDATA[Aanjaney]]></itunes:author><googleplay:owner><![CDATA[aanjaneykumarverma@substack.com]]></googleplay:owner><googleplay:email><![CDATA[aanjaneykumarverma@substack.com]]></googleplay:email><googleplay:author><![CDATA[Aanjaney]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Understanding Memory Allocation: Stack vs. Heap]]></title><description><![CDATA[Navigating Memory Management: A Comparative Exploration of Stack and Heap Allocation]]></description><link>https://aanjaneykumarverma.substack.com/p/understanding-memory-allocation-stack</link><guid isPermaLink="false">https://aanjaneykumarverma.substack.com/p/understanding-memory-allocation-stack</guid><dc:creator><![CDATA[Aanjaney]]></dc:creator><pubDate>Sun, 19 Nov 2023 06:44:22 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F16b7d0c8-9b78-4820-9449-b307ed2d5430_220x220.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When it comes to programming, one fundamental aspect that developers must grapple with is memory allocation. Memory allocation is the process of reserving and managing a computer's memory for various tasks. Two common methods for memory allocation in programming are stack and heap. In this article, we'll delve into the key differences between these two approaches and explore their respective advantages and drawbacks.</p><p>Below is a figure to give you an idea of how the memory layout looks like:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!BKNA!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!BKNA!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 424w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 848w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 1272w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!BKNA!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png" width="500" height="475" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:475,&quot;width&quot;:500,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:&quot;program_in_memory&quot;,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="program_in_memory" title="program_in_memory" srcset="https://substackcdn.com/image/fetch/$s_!BKNA!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 424w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 848w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 1272w, https://substackcdn.com/image/fetch/$s_!BKNA!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3e134447-2ba8-428a-83e7-6dd597b5972b_500x475.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Lets have a look at both of these memories in detail.</p><h3><strong>Stack Memory:</strong></h3><h4><strong>Definition:</strong></h4><p>The stack is a region of a computer's memory that operates in a Last-In, First-Out (LIFO) manner. It is used to store local variables and function call information. The stack memory is managed automatically by the compiler, making it a straightforward and efficient way to allocate and deallocate memory.</p><h4><strong>Characteristics:</strong></h4><ul><li><p><strong>Automatic Management:</strong> Stack memory is managed automatically by the compiler. When a function is called, space is allocated on the stack for local variables, and this space is automatically released when the function exits.</p></li><li><p><strong>Faster Access:</strong> Accessing data on the stack is faster than on the heap because it involves simple pointer manipulation.</p></li></ul><h4><strong>Limitations:</strong></h4><ul><li><p><strong>Fixed Size:</strong> The size of the stack is typically fixed, and exceeding this limit can lead to a stack overflow. This limitation can be a challenge for applications requiring dynamic memory allocation.</p></li></ul><h3><strong>Heap Memory:</strong></h3><h4><strong>Definition:</strong></h4><p>The heap is a region of a computer's memory used for dynamic memory allocation. Unlike the stack, the heap memory requires manual management by the programmer. It provides a more flexible and expansive memory space, allowing for the allocation of memory at runtime.</p><h4><strong>Characteristics:</strong></h4><ul><li><p><strong>Dynamic Allocation:</strong> Memory on the heap can be allocated and deallocated explicitly during the program's execution, providing flexibility in managing memory.</p></li><li><p><strong>Variable Size:</strong> The heap allows for the allocation of variable-sized blocks of memory, making it suitable for applications with unpredictable memory requirements.</p></li></ul><h4><strong>Limitations:</strong></h4><ul><li><p><strong>Manual Management:</strong> Heap memory requires manual management, and failure to deallocate memory properly can result in memory leaks or fragmentation.</p></li><li><p><strong>Slower Access:</strong> Accessing data on the heap is generally slower than on the stack due to the need for explicit pointer manipulation. </p></li></ul><p></p><p>This information indicates that stack is the ideal place for storing and managing local variables &amp; function call information. On the other hand, heap is suitable for dynamic memory allocation and best for applications with varying memory requirements.</p><p>There is this one final piece of information I would like to share. </p><p>Heap memory is shared across all threads of a program, however each thread has its own separate call stack.</p><p>Hence, in scenarios where data needs to be kept private and isolated between threads, utilizing the stack can be a safer choice in a multithreaded program, such as a transaction handler. The stack's thread-specific nature helps prevent unintended interactions between threads, ensuring data integrity and contributing to a more robust and thread-safe design. It's important to balance this choice with an awareness of the stack's size limitations and automatic memory deallocation characteristics.</p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://aanjaneykumarverma.substack.com/subscribe?"><span>Subscribe now</span></a></p>]]></content:encoded></item><item><title><![CDATA[Binary Indexed Tress (BIT)]]></title><description><![CDATA[Part III]]></description><link>https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit-80d</link><guid isPermaLink="false">https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit-80d</guid><dc:creator><![CDATA[Aanjaney]]></dc:creator><pubDate>Sun, 15 Oct 2023 04:30:19 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F16b7d0c8-9b78-4820-9449-b307ed2d5430_220x220.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Over the previous two parts of BIT posts, we have learned about their working and their implementation. We also learned how to implement them for higher dimensions! This final part will discuss how this data structure can be used to support range updates and range queries as well.</p><h4>Range updates and Range Queries</h4><p>We will look at supporting range updates only first. Then we will use that understanding of ours to support range queries too.</p><h5>Range updates</h5><p>Consider that you have a BIT and it contains nothing but <strong>zeroes </strong>at the moment.</p><p>You are given a bunch of queries of the form:</p><pre><code>[l, r, x] -&gt; Add x to each element in the range [l, r]

If we look at our existing implementation of BIT. We can see that if we do point updates, this will take us O((r - l + 1) * log(maxIdx)) time.</code></pre><p>Can we do better?<br>Well, yes! We can mimic the same behavior by making two point updates!</p><pre><code>1. add(l, x)
2. add(r + 1, -x)</code></pre><p>Now, if we want the value of an element at an index i, we can just perform prefix sum using our query function!<br><br>Lets break down these two queries and see why this works?</p><p>The range [0, l - 1] is left untouched by these two queries. Hence, the answer will be correct for that range.<br>The range [l, r] will also be corrected since we added x to l. We will always get the answer x in return. <br>The -x added post r, will cancel out the first operation and return 0 as expected.<br></p><h5>Range Queries</h5><p><br>Cool! So we can do point queries. But what about range queries? How do we support them?<br>In order to support range queries we will require two BITs. Say BIT1 and BIT2.<br>Again, for simplicity we will assume that both have initially nothing but zero values.</p><p>Lets assume we got a query to add x to each element in the range [l, r].</p><p>How do we update these two BITs?</p><p>We will arrive at our answer by backtracking.</p><p>What do we expect when we want to know the sum of values upto ith index.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\n\n\n\n\\text{sum}[i] =\n\\begin{cases}\n0 &amp; \\text{if } i < l \\\\\nx \\cdot (i - (l-1)) &amp; \\text{if } l \\leq i \\leq r \\\\\nx \\cdot (r - l + 1) &amp; \\text{otherwise}\n\\end{cases}\n\n\n\n&quot;,&quot;id&quot;:&quot;DDKJNTHBTK&quot;}" data-component-name="LatexBlockToDOM"></div><p></p><p>We can rewrite this sum as follows:</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\text{sum}[i] =\n\\begin{cases}\n0 \\cdot i - 0 &amp; \\text{if } i < l \\\\\nx \\cdot i - x \\cdot (l-1) &amp; \\text{if } l \\leq i \\leq r \\\\\n0 \\cdot i - (x \\cdot (l-1) - x \\cdot r) &amp; \\text{otherwise}\n\\end{cases}&quot;,&quot;id&quot;:&quot;OZWFMICTZR&quot;}" data-component-name="LatexBlockToDOM"></div><p><br>This now is a difference of two terms.<br>We will store one term in BIT1 and the other in BIT2.</p><p>Then,</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\begin{equation}\n\\text{sum}[i] = \\text{BIT1}[i] * i - \\text{BIT2}[i]\n\\end{equation}\n&quot;,&quot;id&quot;:&quot;AYZKESXFGW&quot;}" data-component-name="LatexBlockToDOM"></div><p><br>Now writing the update queries becomes much simpler.<br><br>For BIT1:</p><pre><code>1. add(l, x)
2. add(r + 1, -x)</code></pre><p>For BIT2:</p><pre><code>1. add(l, x*(l - 1))
2. add(r + 1, -x*r)</code></pre><p>And now, we can perform range queries as well!</p><p>In case of doubts or confusions, revisit the previous sections of this series or list them down in the comments below.</p><p>Happy learning!!</p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://aanjaneykumarverma.substack.com/subscribe?"><span>Subscribe now</span></a></p>]]></content:encoded></item><item><title><![CDATA[Binary Indexed Tress (BIT)]]></title><description><![CDATA[Part II]]></description><link>https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit-71e</link><guid isPermaLink="false">https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit-71e</guid><dc:creator><![CDATA[Aanjaney]]></dc:creator><pubDate>Wed, 27 Sep 2023 04:30:14 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F16b7d0c8-9b78-4820-9449-b307ed2d5430_220x220.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Continuing our Part I discussion, we will be looking at the implementation of this data structure in this post!</p><h4>Implementation</h4><pre><code>class BIT
{
private:
    vector&lt;int&gt; arr;
    int n;

public:
    BIT(int n)
    {
        this-&gt;n = n;
        arr.assign(n + 1, 0);
    }
    BIT(vector&lt;int&gt; const &amp;a) : BIT(a.size())
    {
        for (int i = 1; i &lt;= n; ++i)
        {
            update(i, a[i - 1]);
        }
    }
    void update(int idx, int value)
    {
        while (idx &lt;= n)
        {
            arr[idx] += value;
            idx += idx &amp; -idx;
        }
    }
    int query(ll idx)
    {
        int ans = 0;
        while (idx &gt; 0)
        {
            ans += arr[idx];
            idx -= idx &amp; -idx;
        }
        return ans;
    }
};</code></pre><p>This implementation using 1 based indexing, and is the one we discussed previously. There is a 0 based indexing implementation as well. However, I like this one more.</p><p>The main functions are <strong>`update` </strong>and <strong>`query`.</strong></p><ul><li><p>While updating an index, we push its value to its rightful successors as well.</p></li><li><p>And while querying, we read the contribution of all the eligible ancestors.</p></li></ul><p>There are some other operations as well, which one can include depending on the needs.</p><p>Suppose, you want to read the actual value at an index i. We will need two calls to the query function in order to achieve the same:</p><pre><code>int value = query(i) - query(i - 1);</code></pre><p>This takes <strong>2 * O(logn) </strong>time. However, we can do better.</p><pre><code>int queryPointValue(int idx)
{
    int val = arr[idx];
    if (idx &gt; 0)
    {
        int ancestor = idx - (idx &amp; -idx);
        --idx;
        while (idx != ancestor)
        {
            val -= arr[idx];
            idx -= idx &amp; -idx;
        }
    }
    return val;
}</code></pre><p>The idea is simple. We are subtracting some values obtained from <strong>query(i)</strong> in <strong>query(i-1).</strong></p><p>Both <strong>idx</strong> and <strong>idx - 1</strong> are nodes in a tree. They will reach a common ancestor while traversing up. Once, they arrive at their common ancestor, all the values will cancel out! Hence, we subtract the values till that <strong>ancestor</strong> only and then break.<br>This reduces the time taken to read a point value in half!!</p><ul><li><p>Scaling the tree by a factor c.</p><pre><code>void scale(int c)
    {
        for (int i = 1; i &lt;= n; ++i)
        {
            arr[i] = arr[i] * c;
        }
    }</code></pre><p>This is quite straightforward. We can multiply or divide by a constant <strong>`c` </strong>to scale the tree by a constant factor.</p></li></ul><h4>Handling 2D Data<br></h4><p>While handling 2D data, our update and query functions will change accordingly.<br>At each iteration, we will finish updating our lower dimension first, and then move to the next successor in our higher dimension.</p><p>Here is the update function for 2D data.</p><pre><code>void update(int x, int y, int val) {
  int y1;
  while (x &lt;= max_x) {
    y1 = y;
    while (y1 &lt;= max_y) {
      arr[x][y1] += val;
      y1 += (y1 &amp; -y1);
    }
    x += (x &amp; -x);
  }
}</code></pre><p>Similarly, for querying in 2D we will follow a similar procedure.</p><pre><code>void query(int x, int y) {
  int val = 0;
  int y1;
  while (x &gt;= 0) {
    y1 = y;
    while (y1 &gt;= 0) {
        val += arr[x][y1];
        y1 -= (y1 &amp; -y1);
    }
    x -= (x &amp; -x);
  }
}</code></pre><p>We can also modify BIT to support range updates. However, for that we need to maintain two separate BITs.<br>In case you guys are interested, I&#8217;ll cover them in a separate post.<br></p><div class="poll-embed" data-attrs="{&quot;id&quot;:104888}" data-component-name="PollToDOM"></div><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://aanjaneykumarverma.substack.com/subscribe?"><span>Subscribe now</span></a></p>]]></content:encoded></item><item><title><![CDATA[Binary Indexed Tress (BIT)]]></title><description><![CDATA[Part I]]></description><link>https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit</link><guid isPermaLink="false">https://aanjaneykumarverma.substack.com/p/binary-indexed-tress-bit</guid><dc:creator><![CDATA[Aanjaney]]></dc:creator><pubDate>Tue, 19 Sep 2023 12:34:13 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F16b7d0c8-9b78-4820-9449-b307ed2d5430_220x220.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Binary Indexed Trees (BIT) or Fenwick Trees is a data structure used for data compression. A common use case of this data structure is to store frequencies and performing operations on the cumulative frequencies&#8217; array/ table.</p><p>Lets consider a problem to better understand this data structure:</p><p>Imagine there are n bank accounts and all of them have $10 to begin with. You add some funds into certain bank accounts. Find the sum of balance of bank accounts numbered a to b.</p><p>Clearly, a brute force solution takes <em>O(1)</em> time to add an amount and <em>O(b - a + 1)</em> time to  query the total balance. Can we do any better?</p><p>This is where BIT comes in. They can answer the second problem in </p><p><em>O(log(b) - log(a -1))</em> time.</p><h4>Idea</h4><p>Any number can be written in base 2, or as a sum of powers of two. Similarly, we can break the balance of bank accounts into sum of balance of a subset of these bank accounts. This way, we can iterate over these subsets to get the total balance instead of iterating over the whole range.</p><p>To do this, we isolate the least significant bit from the binary representation of a number (x). Let it be at the position y.</p><p>Then x is responsible for storing balance of all the banks in the range [x - 2<sup>y</sup> +1, x].</p><p>Now, the question is, how do we isolate this position?</p><p>Well, its simply x &amp; -x, where &amp; is bitwise AND, and (-x) is negative x.</p><h5>Proof</h5><p>Let the number be of the form A1B. <strong>`A`</strong> will cover the portion before the least significant bit and <strong>`B`</strong> will the cover the portion after it. The <strong>`1`</strong> between them is the least significant bit. One needs to notice that B will consist of 0s only.</p><p>We need to remember that numbers are stored as 2&#8217;s complement in computers.<br>So, <strong>&#955;</strong> in the proof below is actually the suffix after the sign bit while storing the number, and this suffix is what truly contributes to the answer. The sign bits won&#8217;t contribute anything to the bitwise AND operation.<br></p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\begin{align*}\n\\text{num} &amp;= A1B \\\\\n\\text{num} &amp;= \\sum_{i=0}^{k} a_i 2^i \\\\\n-\\text{num} &amp;= -\\sum_{i=0}^{k} a_i 2^i \\\\\n-\\text{num} &amp;= -2^{k+1} + \\lambda \\\\\n\\lambda &amp;= (2^{k+1} - 1) - \\text{num} + 1 \\\\\n\\lambda &amp;= 1 + 2 + 2^2 + \\ldots + 2^k - \\text{num} + 1 \\\\\n\\lambda &amp;= \\sum_{i=0}^{k} (1 - a_i) 2^i  + 1\\\\\n\\lambda &amp;= A^{-1}0B^{-1} + 1 \\\\\n\\lambda &amp;= A^{-1}1B\n\\end{align*}\n&quot;,&quot;id&quot;:&quot;MTPEDCRWTB&quot;}" data-component-name="LatexBlockToDOM"></div><p>Keeping in mind the above result, we have.</p><div class="latex-rendered" data-attrs="{&quot;persistentExpression&quot;:&quot;\\begin{align*}\n\\text{num} \\, \\&amp; \\,-\\text{num} &amp;= A1B \\, \\&amp; \\, A^{-1}1B \\\\\n&amp;= (0\\ldots0)1(0\\ldots0)\n\\end{align*}\n&quot;,&quot;id&quot;:&quot;DJMYESJUDO&quot;}" data-component-name="LatexBlockToDOM"></div><p>which is nothing but the least significant bit!!</p><p>We have covered all the theory we need to understand BIT now. In the next part of this article, we will look at the implementation of this simple yet powerful data structure. Till then, happy learning!!</p>]]></content:encoded></item><item><title><![CDATA[Binary Search: A Comprehensive Guide]]></title><description><![CDATA[Theory Most of us are familiar with the concept of binary search.]]></description><link>https://aanjaneykumarverma.substack.com/p/binary-search-a-comprehensive-guide</link><guid isPermaLink="false">https://aanjaneykumarverma.substack.com/p/binary-search-a-comprehensive-guide</guid><dc:creator><![CDATA[Aanjaney]]></dc:creator><pubDate>Sun, 10 Sep 2023 07:44:34 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F11178a5c-1539-4f53-93ea-217b628043b7_144x144.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3>Theory</h3><p>Most of us are familiar with the concept of binary search. We take a sorted array as an input, and maintain an active region where the desired number might lie. That&#8217;s more or less the general idea most of us have about this approach.</p><p>However, we can take this idea further. Consider, a function which is monotonic in nature. Here is an example:</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Aanjaney&#8217;s Substack! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p>For simplicity, lets take the domain as the set of integers. We want to find the minimum value of x where f(x) returns 1.</p><p>If we scan through the return values of f(x) for the first 10 integers, the answer array looks like this:</p><pre><code><code>false, false, false, false, false, true, true, true, true, true</code></code></pre><p>Clearly, the answer function is monotonic and hence we can apply binary search here!</p><p>Thus, in order for binary search to work, the search space must look like something of the following form, using a function as described above.</p><pre><code><code>true, true, true, true, false, false, false, .....</code></code></pre><p>Then, we find the point at which true becomes false, using binary search.</p><h3>Implementation</h3><p>There are different ways to go about the implementation. In this blog, we&#8217;ll discuss three. Method 1 and Method 2 are what you call a closed interval implementation. Method 3 is an open interval implementation. I personally prefer Method 3 due to the open interval nature. </p><p>For all the implementations below assume that the answer lies in the range [0, n].</p><h4>Method 1</h4><p>This is what most of us are familiar with.</p><pre><code><code>int left = 0, right = n;
while ( left &lt;= right) {
    int mid = left + (right - left) / 2;
    if (check(mid)) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}
int ans = left - 1;</code></code></pre><p>During the entire execution of the algorithm, we maintain the following invariant:</p><p>[left, right] is the active region in which our answer lies.</p><h4>Method 2</h4><pre><code><code>int ans = 0;
int maxJump = n;
for (int jump = maxJump; jump &gt;= 1; jump /= 2) {
    while (check(ans + jump)) {
        ans = ans + jump;
    }
}
return ans;</code></code></pre><p>We are making bigger jumps when we are far away from the answer, and slowing down as we come closer to it.</p><h4>Method 3</h4><p>This looks almost exactly the same as Method 1, however here we will maintain the following invariant:</p><p>[left, right) is the active region in which our answer lies.</p><p>Notice how right is not included in the active region. </p><pre><code><code>int left = 0, right = n + 1;
while ( left &lt; right) {
    int mid = left + (right - left) / 2;
    if (check(mid)) {
        left = mid + 1;
    } else {
        right = mid;
    }
}
int ans = left - 1;</code></code></pre><p>We update right to mid, in order to maintain the invariant. Also, the inequality changes from <strong>&lt;=</strong> to just <strong>&lt;</strong> , again due to the invariant we have chosen.</p><p>One can use any of the above methods as per their liking. What is more important, is that we understand what is the invariant we are maintaining, and how should the parameters be updated to reflect that. This can help prevent those off by one errors we generally encounter due to the incorrect implementation of the algorithm.</p><p></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://aanjaneykumarverma.substack.com/subscribe?"><span>Subscribe now</span></a></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aanjaneykumarverma.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Aanjaney&#8217;s Substack! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item></channel></rss>