<?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 neemkashu on Medium]]></title>
        <description><![CDATA[Stories by neemkashu on Medium]]></description>
        <link>https://medium.com/@sparjinkust?source=rss-69ea2016ff0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-NnyLqb2IkvQNlzd</url>
            <title>Stories by neemkashu on Medium</title>
            <link>https://medium.com/@sparjinkust?source=rss-69ea2016ff0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:05:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sparjinkust/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[Binary Search with Invariants: Easy and Clear Approach]]></title>
            <link>https://medium.com/@sparjinkust/binary-search-with-invariants-easy-and-clear-approach-c31087d5a79c?source=rss-69ea2016ff0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c31087d5a79c</guid>
            <category><![CDATA[invariants]]></category>
            <category><![CDATA[predicate]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[neemkashu]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 13:18:23 GMT</pubDate>
            <atom:updated>2023-09-22T16:03:41.557Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Struggling </strong>with <strong>Binary Search</strong>? While the algorithm’s core concept is simple, <strong>implementing </strong>it without <strong>errors </strong>can be challenging. This is a guide to a <strong>debugging-free</strong> approach.</p><p>The <strong>core idea</strong> is to use <strong>predicates </strong>and <strong>invariants</strong>, which we’ll explore in <strong>detail</strong>.</p><p><strong>NOTE</strong>: The article assumes that you are <strong>familiar </strong>with the idea of binary search. The aim is to <strong>improve </strong>your <strong>implementation </strong>skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aA2v0ONA_jM7WbwN" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>💡 A couple of concepts</h3><ul><li><strong>Invariant:</strong> some <strong>relation </strong>that will <strong>not change</strong> during the <strong>entire </strong>algorithm</li><li><strong>Binary predicate</strong>: a function that returns <strong>boolean </strong>and is used for the <strong>search</strong></li></ul><h3>📘 Binary Search Blueprint</h3><p>The code is in J<strong>avaScript</strong>, but it looks almost <strong>the same</strong> in other popular languages, if you can <strong>pass a function</strong> as an argument. Also, you <strong>don’t have to worry</strong> about array<strong> index out-of-bounds</strong> errors: they won’t occur.</p><pre>function binarySearch(predicate, arr) {<br>// we will replace &#39;?&#39; with correct code<br>  let l = ? // init left pointer<br>  let r = ? // init right pointer<br><br>  while( ? ) { // the end of the search<br>    let m = ? // middle pointer<br><br>    if (predicate(arr[m])) {<br>      ? // adjust pointers for a predicate true value<br>    } else {<br>      ? // and for the false value<br>    }<br>  }<br>  // return some number at the end<br>}</pre><p><strong>EVERYTHING </strong>in this prototype can be written without <strong>trial and error, </strong>without “oh, should it be +1 or -1” or rounding problems.</p><h3>❓ Problem Statement</h3><p>Let’s solve the following task</p><blockquote>Given an array of <strong>integers</strong>, find the <strong>index</strong> of the <strong>first odd</strong> number in the array. <strong>All even </strong>numbers in the array are positioned <strong>to the left</strong> of the <strong>odd </strong>numbers.</blockquote><blockquote><strong>Example</strong>: [2 6 4 5 9 1 1] <strong>Answer</strong>: 3</blockquote><blockquote><strong>Example</strong>: [4 4 4] <strong>Answer</strong>: -1 (the index is not found)</blockquote><blockquote><strong>Example</strong>: [3 7 5] <strong>Answer</strong>: 0</blockquote><p>We’ll <strong>fill </strong>the blueprint’s <strong>gaps </strong>in the order of <strong>reasoning</strong>.</p><h3>➡️Solution Step-by-Step ️➡️</h3><h4>Predicate ⚖️</h4><p>We will write a function that <strong>changes </strong>from false totrue at the <strong>border </strong>where the <strong>answer </strong>is located. Let’s use the following <strong>markers</strong>:</p><ul><li>false as <strong>minus</strong>, <strong>-</strong></li><li>true as <strong>plus</strong>, <strong>+</strong></li></ul><p>The <strong>predicate</strong> indicates we<strong> </strong>are<strong> to the left</strong> or <strong>to the right of</strong> the <strong>desired</strong> value.</p><pre>  - - - + + + +<br>[ 2 6 4 5 9 1 1 ]<br><br>const predicate = (num) =&gt; num % 2 !== 0<br><br>predicate(5) === true<br>predicate(4) === false</pre><p>Also, be sure that the <strong>predicate </strong>value changes <strong>at most once</strong> amoung the array values. Consider the <strong>possible </strong>predicate values:</p><pre>[ - - - - - + + ]<br>[ - - - - - - - ]<br>[ + + + + + + + ]</pre><p><em>Note 1</em>: you may want to choose a <strong>predicate </strong>that <strong>changes </strong>from true to false at some index, for example, if the task is to find the <strong>last even</strong> number. But you <strong>don’t have to</strong>: just choose what to return either <strong>l</strong> or <strong>r</strong>, as we’ll see later.</p><p><em>Note 2: Why Predicate? — </em>That makes the implementation <strong>independent</strong> of the specific <strong>problem or task</strong>. Find a few other <strong>examples </strong>of a <strong>predicate </strong>in the<strong> Examples </strong>section.</p><h4>Invariants 🔒</h4><p>You need to choose <strong>statements </strong>about the <strong>left </strong>and <strong>right </strong>boundaries (<strong>l</strong> and <strong>r</strong>) that you will keep <strong>true </strong>during the <strong>entire </strong>algorithm. Let’s say these statements are:</p><ul><li><strong>l points to minus</strong></li><li><strong>only minuses</strong> are to the <strong>left </strong>of <strong>l</strong></li><li><strong>r points to plus</strong></li><li><strong>only pluses </strong>are<strong> to the right of </strong><strong>r</strong></li></ul><p>In markdown illustration</p><pre>l points to minuses only<br>  l     l<br>[ - - - - + + + + + ]<br><br>r points to pluses only<br>          r       r<br>[ - - - - + + + + + ]</pre><h4>Initial values 🌱</h4><p>Let’s introduce a small <strong>convention</strong>. Let the predicate give a <strong>minus</strong> to the <strong>left of the array</strong>, and a <strong>plus </strong>to the <strong>right of the array</strong>. These checks will <strong>never be run </strong>in the code, but they will help to immediately place <strong>l</strong> and <strong>r</strong></p><pre>- - - - - - + + + + + + +<br>     [2 6 4 5 9 1 1]</pre><p>So, place <strong>l</strong> and <strong>r</strong> to satisfy the <strong>invariants</strong>:</p><ul><li><strong>l</strong> points to “index” <strong>–1</strong>: we are sure that <strong>only minuses </strong><strong>– </strong>are to <strong>the left of index 0</strong></li><li><strong>r</strong> points to <strong>the right </strong>of the<strong> last </strong>index: the only <strong>known plus </strong><strong>+</strong> at the <strong>initial </strong>state</li></ul><pre>- - -               + + +<br>     [2 6 4 5 9 1 1]<br>    l               r</pre><p>Thus, the <strong>initial values </strong>are ready.</p><pre>function binarySearch(predicate, arr) {<br><br>  let l = -1<br>  let r = arr.length<br><br>// the rest of the code<br>}</pre><h4>Loop test condition 🔄</h4><p>The <strong>invariant</strong> gives a clue when to <strong>exit the loop</strong>. Illustrate the <strong>closest</strong> possible positions of <strong>l</strong> and <strong>r</strong> still satisfing the <strong>invariant</strong>.</p><pre>l rightmost position<br><br>        l<br>[ - - - - + + + + + ] <br>          r<br><br>r leftmost position</pre><p>That’s it! <strong>End</strong> the loop when <strong>l</strong> and <strong>r </strong>are <strong>neighbors</strong>.</p><pre>  while(l + 1 &lt; r) {<br>    // code<br>  }</pre><h4>Predicate returns true ✅</h4><p>We somehow calculated the <strong>middle </strong><strong>m</strong> (about it later) and perform a check predicate(arr[m]). Consider the result which equals <strong>plus </strong><strong>+ , </strong>or<strong> </strong>true</p><pre>- - -       m        + + +<br>     [      +       ]<br>    l                r</pre><p>The <strong>target</strong> is somewhere between <strong>-</strong> and <strong>+</strong> so we will <strong>change </strong>the<strong> right</strong> pointer. Keep the <strong>invariant </strong>true: <strong>r</strong> points to <strong>plus</strong> <strong>+</strong> and only <strong>pluses </strong>are to the <strong>right</strong>.</p><pre>- - -       m        + + +<br>     [      + + + + ]<br>    l       r</pre><p>Code update:</p><pre>    if (predicate(arr[m])) {<br>      r = m<br>    }</pre><h4>Predicate returns false ❌</h4><p>If the result of predicate(arr[m]) equals <strong>minus</strong> <strong>- , </strong>or<strong> </strong>false</p><pre>- - -       m        + + +<br>     [      -       ]<br>    l                r</pre><p>we will change the <strong>left </strong>pointer. The <strong>invariant</strong>: <strong>l</strong> points to <strong>minus </strong>and only <strong>minuses </strong>are to the <strong>left </strong>of <strong>l</strong></p><pre>- - -       m        + + +<br>     [- - - -       ]<br>            l        r</pre><p>Code update:</p><pre>// ...<br>      else {<br>      l = m<br>    }</pre><h4>What is m equal to? ➗</h4><p><strong>m</strong> is the middle between <strong>l</strong> and <strong>r</strong> but we have to <strong>round </strong>it up or down.</p><pre>m = Math.floor((l + r) / 2)<br><br>           vs<br><br>m = Math.ceil((l + r) / 2)</pre><p>Here comes the reason why our <strong>invariant</strong> is the <strong>best</strong>: the rounding does not matter. <strong>Consider </strong>such a situation: <strong>l</strong> и <strong>r</strong> are <strong>one iteration from the end</strong> of the loop. Despite of rounding, <strong>m</strong> points right between <strong>l</strong> and <strong>r</strong> so the next iteration <strong>ends</strong> the loop.</p><pre>- - -         m          + + +      - - -         m        + + +<br>     [- - - - - + + + + ]       ---&gt;     [- - - - - + + + ]<br>            l   r                                 l r<br><br>- - -         m          + + +      - - -         m        + + +<br>     [- - - - + + + + + ]       ---&gt;     [- - - - + + + + ]<br>            l   r                               l r</pre><p>Also, you <strong>automatically avoid</strong> the problem of an <strong>infinite loop</strong>.</p><h3>🚀 Binary Search Code</h3><p>The loop ends when <strong>l</strong> points to the<strong> last minus</strong> and <strong>r</strong> points to the <strong>first plus</strong>. The task is to find the <strong>first odd number</strong> so it is preferable to return <strong>r</strong> in our case.</p><pre>function binarySearch(predicate, arr) {<br><br>  let l = -1<br>  let r = arr.length<br><br>  while(l + 1 &lt; r) {<br>    let m = Math.floor((l + r) / 2)<br><br>    if (predicate(arr[m])) {<br>      r = m<br>    } else {<br>      l = m<br>    }<br>  }<br>  return r<br>}</pre><h4>Edge Cases and Problem Solution ⚠️</h4><p>Remember the second <strong>test case</strong> of the task</p><blockquote><strong>Example</strong>: <em>[4 4 4]</em> <strong>Answer</strong>: <em>-1</em> (the index is not found)</blockquote><p>In this case, our <strong>binary search</strong> returns 3, and that’s intentional. Do <strong>not include</strong> task <strong>details </strong>into binary search code, just <strong>handle </strong>the <strong>results</strong> in the <strong>solution</strong>.</p><pre>function solution(arr) {<br><br>  const predicate = (num) =&gt; num % 2 !== 0<br>  const firstOdd = binarySearch(predicate, arr)<br>  <br>  return firstOdd &lt; arr.length ? firstOdd : -1<br>}</pre><p>Next, let’s explore the <strong>out-of-bounds</strong> error. You <strong>access </strong>the array’s elements only through index <strong>m</strong>. The following relations ensure that <strong>m</strong> is always <strong>greater than </strong><strong>l</strong> and is <strong>less than </strong><strong>r</strong>. Thus, <strong>m</strong> never equals <strong>-1</strong> or an array length</p><pre>m = Math.floor((l + r) / 2)<br>l + 1 &lt; r</pre><p>Examine how <strong>m</strong> changes <strong>during the search</strong> in this array.</p><blockquote><strong>Example</strong>: <em>[4 4 4 6 8 8]</em></blockquote><pre>m = 2<br>-     m       +<br> [4 4 4 6 8 8]<br>l             r<br><br>m = 4<br>- - - -   m   +<br> [4 4 4 6 8 8]<br>      l       r<br><br>m = 5<br>- - - - - - m +<br> [4 4 4 6 8 8]<br>          l   r<br><br>end of the loop<br>- - - - - - - +<br> [4 4 4 6 8 8]<br>            l r</pre><p>You can obtain a <strong>similar result</strong> when considering [1 3 5 7 9]: the <strong>minimum </strong>value of <strong>m</strong> is <strong>0</strong> just before the end of the search.</p><h3>📝 Examples</h3><h4>Task 1</h4><blockquote>An array of <strong>integers </strong>is sorted in a <strong>non-decreasing</strong> order. Find the index of an <strong>arbitrary target </strong>number. If the array includes <strong>several</strong> numbers <strong>equal to </strong>the<strong> target</strong> return the index of the <strong>first </strong>one.</blockquote><blockquote><strong>Example</strong>: <em>9, [-1 0 1 5 7]</em> <strong>Answer</strong>: <em>-1</em>(the index is not found)</blockquote><blockquote><strong>Example</strong>: <em>2, [4 4 4]</em> <strong>Answer</strong>: <em>-1</em> (the index is not found)</blockquote><blockquote><strong>Example</strong>: <em>8, [-3 5 8 8 8 9]</em> <strong>Answer</strong>: <em>2</em></blockquote><p><strong>Predicate: c</strong>heck that it returns <strong>only pluses</strong>, <strong>only minuses</strong> or <strong>changes</strong> once at the edge</p><pre>const predicate = (num) =&gt; num &gt;= target<br><br>Target: 9<br>  - - - - -<br>[-1 0 1 5 7]<br><br>Target: 2<br> + + +<br>[4 4 4]<br><br>Target: 8<br>  - - + + + +<br>[-3 5 8 8 8 9]<br></pre><p><strong>Solution</strong></p><pre>function solution(arr, target) {<br><br>  const predicate = (num) =&gt; num &gt;= target<br>  const greaterOrEqualToTarget = binarySearch(predicate, arr)<br>  <br>  if (greaterOrEqualToTarget &gt;= arr.length) return -1<br>  return arr[greaterOrEqualToTarget] !== target ? -1 : greaterOrEqualToTarget<br>}</pre><h4>Task 2</h4><blockquote>Given an array of <strong>integers </strong>sorted in a <strong>non-decreasing</strong> order find the index of the <strong>last negative</strong> number.</blockquote><blockquote><strong>Example</strong>: <em>[-3 0 1 5 7]</em> <strong>Answer</strong>: <em>0</em></blockquote><blockquote><strong>Example</strong>: <em>[4 4 4]</em> <strong>Answer</strong>: <em>-1</em> (the index is not found)</blockquote><blockquote><strong>Example</strong>: <em>[-9 -8 -1]</em> <strong>Answer</strong>: <em>2</em></blockquote><p><strong>Predicate</strong>: let the binary search find the<strong> first non-negative</strong> number and <strong>handle</strong> the result in the solution.</p><pre>const predicate = (num) =&gt; num &gt;= 0<br><br>  - + + + +<br>[-3 0 1 5 7]<br><br> + + +<br>[4 4 4]<br><br>  -  -  -<br>[-9 -8 -1]</pre><p><strong>Solution</strong></p><pre>function solution(arr) {<br>  const predicate = (num) =&gt; num &gt;= 0<br>  const lastNonNegative = binarySearch(predicate, arr)<br><br>  return lastNonNegative - 1<br>}</pre><h3>🎉 Conclusion</h3><p>Implement <strong>binary search function</strong> by these steps:</p><ul><li>write a <strong>predicate</strong></li><li>choose <strong>invariants </strong>for<strong> left </strong>and<strong> right </strong>pointers (<em>you know which are the best</em>)</li><li><strong>rely on</strong> invariants to <strong>init</strong> the pointers</li><li><strong>rely on</strong> invariants to write the <strong>loop exit condition</strong></li><li>find the <strong>middle</strong></li><li>find the <strong>predicate </strong>value at the <strong>middle </strong>and <strong>change </strong>one of the pointers</li><li><strong>return </strong>one of the pointers from the function</li></ul><p>After a bit of practice <strong>binary search</strong> will become a <strong>reliable tool </strong>in your hands.</p><p><em>Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c31087d5a79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>