<?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 Ramnayan Yadav on Medium]]></title>
        <description><![CDATA[Stories by Ramnayan Yadav on Medium]]></description>
        <link>https://medium.com/@ramnayan699?source=rss-c51f36d38b90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5YlCpHJ-Ze-pfHPMaglaMw.jpeg</url>
            <title>Stories by Ramnayan Yadav on Medium</title>
            <link>https://medium.com/@ramnayan699?source=rss-c51f36d38b90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:40:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramnayan699/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[Breadth-First Thinking: Mastering Level Order Traversal]]></title>
            <link>https://medium.com/@ramnayan699/breadth-first-thinking-mastering-level-order-traversal-53054b731b33?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/53054b731b33</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 14:49:37 GMT</pubDate>
            <atom:updated>2026-07-23T14:49:37.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vAfIM7pJrG0VstjkgWfyag.png" /></figure><p>In this post, I am going to explain the level order traversal and how it’s works and it’s inner flowchart with an example.</p><p>As name suggested <strong>level order traversal, </strong>searching elements in a binary tree level by level. Binary tree root node start from level zero(it’s depend on you) and immediate nodes are at level 1, immediate after immediate node are level 2 etc. For instance find the bellow given example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_gogKslJl9PUrM04qVX8w.jpeg" /></figure><p>As you can see in Fig 2.0, the search starts from the root node (level 0) and then moves to the child nodes (level 1), and so on. To store the elements level by level, two variables are required: the first is a result[] array, and the second is a queue[].</p><p>The result variable will store the sublists level-wise, and the queue array will store the tree nodes level-wise, following the FIFO rule.</p><p>A queue is a data structure that stores items following the First In, First Out (FIFO) rule. The item that comes in first is the one that goes out first. For instance, consider a number of people lined up at an ATM machine to withdraw money.</p><p>Here’s a flowchart of the level order traversal algorithm, matching the tree and level lists from your diagram:This maps directly to your tree example: it starts with queue = [10] and result = [], then loops — grabbing the current level&#39;s size, dequeuing each node into result while enqueuing its children — until the queue empties, giving you [[10], [20,30], [40,50,60,70], [80,90,100,110]].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9mHhnvDo5qCbLZMZbDz6A.png" /></figure><p>Find the javascript code of level order traversal and how it working.</p><pre>var levelOrder = function(node){<br>    if(node == null){<br>        return;<br>    }<br>    <br>    let queue = [];<br>    let result = [];<br>    queue.push(node);<br>    let level = 0;<br>    while( queue.length &gt; 0){<br>        let size = queue.length;<br>        <br>        for(let i=0;i&lt;size;i++){<br>            let node = queue.shift();<br>            result[level]= result[level] || [];<br>            result[level].push(node.data);<br><br>            if(node.left){<br>                queue.push(node.left);<br>            }<br>            if(node.right){<br>                queue.push(node.right);<br>            }<br>        }<br><br>        level++;<br>    }<br><br>    return result;<br>}<br><br>levelOrder(root);</pre><p>I hope you have understand the working of the level order traversal tree algorithm if you have still any doubts you can comment or can reach out the blogs: <a href="https://www.geeksforgeeks.org/dsa/level-order-tree-traversal/">gfg</a> <a href="https://takeuforward.org/data-structure/level-order-traversal-of-a-binary-tree">takeuforward</a> <a href="https://www.enjoyalgorithms.com/blog/level-order-traversal-of-binary-tree">ea</a>.</p><p>Thanks for here if you have any suggestion please put in the comments 🧑🏼‍💻🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53054b731b33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sieve of Eratosthenes Algorithm]]></title>
            <link>https://medium.com/@ramnayan699/sieve-of-eratosthenes-algorithm-1060b18806cf?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/1060b18806cf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 12:06:53 GMT</pubDate>
            <atom:updated>2026-07-08T09:05:13.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X48ene-_Scg-f5Sq" /><figcaption>Photo by <a href="https://unsplash.com/@liunidis?utm_source=medium&amp;utm_medium=referral">Leonardo André</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Finding the prime numbers between the 2 to n as given input(n) value. We know the usual solution for finding an number is prime or not in O(log(n)) time complexity.</p><pre>function prime(n){<br>  for(let i=2;i&lt;=Math.sqrt(n);i++){<br>    if(n%i===0) return false;<br>  }<br>  return true;<br>}<br><br>console.log(prime(6)) // false</pre><p>But finding the prime numbers in a given range then the time complexity will be O(n(log(n)) and if the number is greater than or equal to (10*5) it’s to hard and slow computation.</p><pre>function prime(n){<br>  for(let i=2;i&lt;=Math.sqrt(n);i++){<br>    if(n%i===0) return false;<br>  }<br>  return true;<br>}<br><br>function primeNumbers(num){<br>  let result = [];<br>  for(let i=2;i&lt;num;i++){<br>    if(prime(i)){<br>      result.push(i);<br>    }<br>  }<br>  return result;<br>}<br><br>console.log(primeNumbers(10)) //[2,3,5,7]</pre><h4>Sieve Eratosthenes Algorithm find the solution to overcome from the time complexity O(nlog(n) to O(nlog(log(n))).</h4><p>Explanation:</p><p>1: Initialize an object and stores the keys from 2-n with default value 1 for all. for instance n = 5, obj = {2:1,3:1,4:1}</p><p>2: Start finding prime, from i=2 and update the object key value from 1 to 0 with all multiple of x and exclude x.</p><p>3: Repeat step 2, from 2 to &lt;num.</p><p>4:Final object will contain the prime numbers result which keys value will be 1. for instance n = 5 obj={2:1,3:1,4:0}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*ilPZUYYzBJ7u7PM-.png" /></figure><pre><br>function prime(n){<br>  for(let i=2;i&lt;=Math.sqrt(n);i++){<br>    if(n%i===0) return false;<br>  }<br>  return true;<br>}<br><br>function primeNumbers(num){<br>  let numbers = {};<br>  for(let k=2;k&lt;num;k++){<br>    numbers[k] =1;<br>  }<br>  <br>  for(let i=2;i&lt;num;i++){<br>    if(prime(i)){<br>      for(let j=2*i;j&lt;num;j+=i){<br>        numbers[j]=0;<br>      }<br>    }<br>  }<br>  return numbers;<br>}<br><br>console.log(primeNumbers(20)) <br>// { 10: 0, 11: 1, 12: 0, 13: 1, 14: 0, 15: 0, 16: 0, 17: 1, 18: 0, 19: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 0, 7: 1, 8: 0, 9: 0 }</pre><p>I hope you have got an idea how this algorithm working, if you still have any doubts you can comment or refer the blogs:</p><p><a href="https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html">1: https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html</a></p><p>2: <a href="https://www.geeksforgeeks.org/dsa/sieve-of-eratosthenes/">https://www.geeksforgeeks.org/dsa/sieve-of-eratosthenes/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1060b18806cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the starting and ending indices of all repeated characters from a string]]></title>
            <link>https://medium.com/@ramnayan699/find-the-starting-and-ending-indices-of-all-repeated-characters-from-a-string-58ec57b9ee7f?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ec57b9ee7f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 06:54:18 GMT</pubDate>
            <atom:updated>2026-06-15T16:06:55.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ya9k0dMnJZfBwsul" /><figcaption>Photo by <a href="https://unsplash.com/@linsartistry?utm_source=medium&amp;utm_medium=referral">Lino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s understand the problem before before moving to the solution. this is state that in a given string we have to find the repeated character starting and ending index(repeated character should be continuous).</p><p>For instance:</p><pre>let str =&quot;hellooooloo&quot;;<br>let res = findRepeated(str);<br>console.log(res) // [(2,3), (4,7), (9,10)]<br><br>function findRepeated(str){<br>    let res = [];<br>    let start = 0;<br>    let end = 1;<br>    <br>    while(start&lt;=end &amp;&amp; end&lt;str.length){<br>        if(str[start]===str[end]){<br>            let diff =  end - start;<br>            if(diff==1 &amp;&amp; end === str.length-1){<br>                res.push([start,end]);<br>            }<br>            end++;<br>        }else{<br>            let diff =  end - start;<br>            if(diff&gt;1){<br>                res.push([start,end-1]);<br>            }<br>            start = end;<br>            end++;<br>        }<br>    }<br>    return res;<br>}<br><br>findRepeated(input);</pre><p>Time complexity of this problem is linear O(n).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ec57b9ee7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tortoise Wins Again: Floyd’s Cycle Detection Algorithm Explained]]></title>
            <link>https://medium.com/@ramnayan699/the-tortoise-wins-again-floyds-cycle-detection-algorithm-explained-5cdfb517c7c3?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cdfb517c7c3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 05:50:53 GMT</pubDate>
            <atom:updated>2026-06-04T05:50:53.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EP2RoE5_q0_qSGgm88mug.jpeg" /></figure><p>Given an linked list where the starting point of that is denoted by head, and there may or may not present cycle for an instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7-DWbqVQXqyse4Gwf4TPg.png" /></figure><p>In the above given example, we have need to find the C node that forms an cycle, starting point of the cycle.</p><p>Let’s understand the famous algorithm to find the Cycle in linked list: <strong>Floyd’s Cycle Algorithm or Tortoise And Hare algorithm. </strong>in order to move on explanation we have to find the two things 1- is cycle present or not if yes then 2- starting position of the linked list node that form the cycle.</p><p><strong>Step 1 to find the cycle in linked list</strong>:</p><p>1: Initialize two variables slow and fast.</p><p>2: Starting point of the two variables is <strong>head</strong>.</p><p>3: Slow pointer move one step at a time.</p><p>4: Fast pointer move two steps at a time.</p><p>5: check slow and fast any of them point to same before any one(or both) reach null.</p><p>6: If both they points to same node at any point of their journey, it’s indicate that cycle indeed exist in the linked list.</p><p>7: If we get null, it’s indicates that their is no cycle exist in the linked list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6uKhJgK9kVUcmMWU.png" /></figure><p>Now, that we have figured out if there is a cycle present in the linked list, for the next step we need to find out the starting point of cycle, i.e., <strong>C</strong>.</p><p>Step 2 to find the starting point of the cycle:</p><p>1: Reset the slow pointer with the head of the linked list</p><p>2: Move slow and fast one step at time.</p><p>3: The point they will meet at will be the starting point of the cycle.</p><pre>// Presence of cycle<br>public boolean hasCycle(ListNode head) {<br>    ListNode slow = head;<br>    ListNode fast = head;<br><br>    while(fast != null &amp;&amp; fast.next != null){<br>        slow = slow.next;<br>        fast = fast.next.next;<br>        if(slow==fast){<br>            return true;<br>        }<br>    }<br><br>    return false;<br>}<br><br><br>// Assuming there is a cycle present and slow and fast are point to their meeting point<br>slow = head;<br>while(slow!=fast){<br>    slow = slow.next;<br>    fast = fast.next;<br>}<br><br>return slow; // the startIing point of the cycle.</pre><h4>Famous problems:</h4><ul><li><a href="https://leetcode.com/problems/linked-list-cycle/">Linked List Cycle (EASY)</a></li><li><a href="https://leetcode.com/problems/happy-number/">Happy Number (Easy)</a></li><li><a href="https://leetcode.com/problems/find-the-duplicate-number/">Find the Duplicate Number (Medium)</a></li><li><a href="https://leetcode.com/problems/linked-list-cycle-ii/">Linked List Cycle II</a></li></ul><p>If you want to explore more about this algorithm please find the <a href="https://www.geeksforgeeks.org/dsa/detect-loop-in-a-linked-list/"><em>gfg </em></a><a href="https://takeuforward.org/data-structure/detect-a-cycle-in-a-linked-list">takeuforward</a> and <a href="https://cp-algorithms.com/others/tortoise_and_hare.html">cp-algorithm</a>🙌🧑‍💻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cdfb517c7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying JavaScript Script Loading: Async and Defer]]></title>
            <link>https://medium.com/@ramnayan699/demystifying-javascript-script-loading-async-and-defer-c3ce62110607?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ce62110607</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 17:12:30 GMT</pubDate>
            <atom:updated>2026-06-04T01:07:15.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeL8dtpeVIf627ZQ-s95-Q.png" /></figure><p>Websites contain the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script"><strong>&lt;script /&gt;</strong></a> to make the web page more dynamic and interactive, aften <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script"><strong>&lt;script /&gt;</strong></a> reside end of the body-content/page and some time in HTML head, it’s depends on the requirements.</p><p>When browser start loading the <a href="https://en.wikipedia.org/wiki/HTML"><strong>HTML</strong></a> and comes acrross the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script"><strong>&lt;script&gt;…&lt;/script&gt;</strong></a> tag, it’s can’t continue building the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model"><strong>DOM</strong></a>. it must wait for script execution. Same thing happen with external <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script"><strong>&lt;script src=”…”&gt;</strong></a>: the browser wait for script to download, execute the downloaded script, and only then it can process the rest of the page.</p><p>That is leads the two major issue:</p><p>1: Scripts can’t see <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model"><strong>DOM</strong></a> elements below them, so they can’t add handlers etc.<br>2: If there’s a bulky script at the top of the page, it “blocks the page”. Users can’t see the page content till it downloads and runs:</p><pre>&lt;p&gt;...content before script...&lt;/p&gt;<br><br>&lt;script src=&quot;https://javascript.info/article/script-async-defer/long.js?speed=1&quot;&gt;&lt;/script&gt;<br><br>&lt;!-- This isn&#39;t visible until the script loads --&gt;<br>&lt;p&gt;...content after script...&lt;/p&gt;</pre><p>For instance, we can put the script bellow of the body-content/page. Then it can easly able to see the above, so it does not block the content to showing.</p><pre>&lt;body&gt;<br>  ...all content is above the script...<br><br>  &lt;script src=&quot;https://javascript.info/article/script-async-defer/long.js?speed=1&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><p>But this solution is for from perfect. For example, the browser notices the script(and can start downloading it) only after it downloaded the full HTML document. That may be noticeable delay.</p><p>Such thing is invisible for the people using fast internet users, but slow internet user can face the major delay and can’t load the full page. So luckily, there are two script props for to over come this issue for external scripts &lt;script src=”…&quot;&gt;&lt;/script&gt; (not for inline scripts) are <strong>async </strong>and <strong>defer.</strong></p><h4>defer:</h4><p>The <strong>defer </strong>props tells to the browser not wait for the script download. Instead, the browser continue to process the HTML document, build the DOM.</p><pre>&lt;p&gt;...content before script...&lt;/p&gt;<br><br>&lt;script defer src=&quot;https://javascript.info/article/script-async-defer/long.js?speed=1&quot;&gt;&lt;/script&gt;<br><br>&lt;!-- visible immediately --&gt;<br>&lt;p&gt;...content after script...&lt;/p&gt;</pre><p>In other words:</p><p>1: Scripts with <strong>defer</strong> never block the page.</p><p>2: Script with <strong>defer</strong> always execute when the DOM is ready(but before the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event"><strong>DOMContentLoaded</strong></a> event).</p><p>Follow example:</p><pre>&lt;p&gt;...content before scripts...&lt;/p&gt;<br><br>&lt;script&gt;<br>  document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; alert(&quot;DOM ready after defer!&quot;));<br>&lt;/script&gt;<br><br>&lt;script defer src=&quot;https://javascript.info/article/script-async-defer/long.js?speed=1&quot;&gt;&lt;/script&gt;<br><br>&lt;p&gt;...content after scripts...&lt;/p&gt;</pre><ol><li>The page content shows up immediately.</li><li>DOMContentLoaded event handler waits for the deferred script. It only triggers when the script is downloaded and executed.</li></ol><p><strong>Deferred scripts keep their relative order, just like regular scripts.</strong></p><p>Let’s say, we have two deferred scripts: the long.js and then small.js:</p><pre>&lt;script defer src=&quot;https://javascript.info/article/script-async-defer/long.js&quot;&gt;&lt;/script&gt;<br>&lt;script defer src=&quot;https://javascript.info/article/script-async-defer/small.js&quot;&gt;&lt;/script&gt;</pre><p>Browsers scan the page for scripts and download them in parallel, to improve performance. So in the example above both scripts download in parallel. The small.js probably finishes first.</p><p>…But the defer attribute, besides telling the browser “not to block”, ensures that the relative order is kept. So even though small.js loads first, it still waits and runs after long.js executes.</p><p>That may be important for cases when we need to load a JavaScript library and then a script that depends on it.</p><p><strong>The </strong><strong>defer attribute is only for external scripts</strong></p><p>The defer attribute is ignored if the &lt;script&gt; tag has no src.</p><h4>async:</h4><p>The async attribute is somewhat like defer. It also makes the script non-blocking. But it has important differences in the behavior.</p><p>The async attribute means that a script is completely independent:</p><ul><li>The browser doesn’t block on async scripts (like defer).</li><li>Other scripts don’t wait for async scripts, and async scripts don’t wait for them.</li><li>DOMContentLoaded and async scripts don’t wait for each other:</li><li>DOMContentLoaded may happen both before an async script (if an async script finishes loading after the page is complete)</li><li>…or after an async script (if an async script is short or was in HTTP-cache)</li></ul><p>In other words, async scripts load in the background and run when ready. The DOM and other scripts don’t wait for them, and they don’t wait for anything. A fully independent script that runs when loaded. As simple, as it can get, right?</p><p>Here’s an example similar to what we’ve seen with defer: two scripts long.js and small.js, but now with async instead of defer.</p><p>They don’t wait for each other. Whatever loads first (probably small.js) – runs first:</p><pre>&lt;p&gt;...content before scripts...&lt;/p&gt;<br><br>&lt;script&gt;<br>  document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; alert(&quot;DOM ready!&quot;));<br>&lt;/script&gt;<br><br>&lt;script async src=&quot;https://javascript.info/article/script-async-defer/long.js&quot;&gt;&lt;/script&gt;<br>&lt;script async src=&quot;https://javascript.info/article/script-async-defer/small.js&quot;&gt;&lt;/script&gt;<br><br>&lt;p&gt;...content after scripts...&lt;/p&gt;</pre><ul><li>The page content shows up immediately: async doesn’t block it.</li><li>DOMContentLoaded may happen both before and after async, no guarantees here.</li><li>A smaller script small.js goes second, but probably loads before long.js, so small.js runs first. Although, it might be that long.js loads first, if cached, then it runs first. In other words, async scripts run in the “load-first” order.</li></ul><p>Async scripts are great when we integrate an independent third-party script into the page: counters, ads and so on, as they don’t depend on our scripts, and our scripts shouldn’t wait for them:</p><pre>&lt;!-- Google Analytics is usually added like this --&gt;<br>&lt;script async src=&quot;https://google-analytics.com/analytics.js&quot;&gt;&lt;/script&gt;</pre><p><strong>The </strong><strong>async attribute is only for external scripts</strong></p><p>Just like defer, the async attribute is ignored if the &lt;script&gt; tag has no src.</p><h4>Dynamic Script:</h4><p>There’s one more important way of adding a script to the page.</p><p>We can create a script and append it to the document dynamically using JavaScript:</p><pre>let script = document.createElement(&#39;script&#39;);<br>script.src = &quot;/article/script-async-defer/long.js&quot;;<br>document.body.append(script); // (*)</pre><p>The script starts loading as soon as it’s appended to the document (*).</p><p><strong>Dynamic scripts behave as “async” by default.</strong></p><p>That is:</p><ul><li>They don’t wait for anything, nothing waits for them.</li><li>The script that loads first — runs first (“load-first” order).</li></ul><p>This can be changed if we explicitly set script.async=false. Then scripts will be executed in the document order, just like defer.</p><p>In this example, loadScript(src) function adds a script and also sets async to false.</p><p>So long.js always runs first (as it’s added first):</p><pre>function loadScript(src) {<br>  let script = document.createElement(&#39;script&#39;);<br>  script.src = src;<br>  script.async = false;<br>  document.body.append(script);<br>}<br><br>// long.js runs first because of async=false<br>loadScript(&quot;/article/script-async-defer/long.js&quot;);<br>loadScript(&quot;/article/script-async-defer/small.js&quot;);</pre><p>Without script.async=false, scripts would execute in default, load-first order (the small.js probably first).</p><p>Again, as with the defer, the order matters if we’d like to load a library and then another script that depends on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ce62110607" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2487. Remove Nodes From Linked List]]></title>
            <link>https://medium.com/@ramnayan699/2487-remove-nodes-from-linked-list-50834cbe8c92?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/50834cbe8c92</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Sat, 30 May 2026 18:39:49 GMT</pubDate>
            <atom:updated>2026-05-30T18:40:28.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wijKGmMe1XLe2KOW" /><figcaption>Photo by <a href="https://unsplash.com/@jasonwong23?utm_source=medium&amp;utm_medium=referral">Jason W</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post i’m gone explain liked list an famous leetcode problem that is “**Remove Nodes from linked list**”.</p><p>Problem Statement:<br>You are given the head of a linked list.</p><p>Remove every node which has a node with a greater value anywhere to the right side of it.</p><p>Return the head of the modified linked list.</p><p>Example 1:</p><p>Input: head = [5,2,13,3,8]<br>Output: [13,8]<br>Explanation: The nodes that should be removed are 5, 2 and 3.<br>- Node 13 is to the right of node 5.<br>- Node 13 is to the right of node 2.<br>- Node 8 is to the right of node 3.</p><p>Explanation:<br>In this problem statement state that remove the nodes which have the right side (any place) element greater than. let’s understand with given example. <br>- Node 13 is the right side of the 5,2 nodes thats why 2,5 should be remove.<br>- Node 8 is the right side of 3 node thats why 3 should be remove.</p><p>final result would be [13,8]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*Qhp57eFkQjSKyEG0.png" /></figure><p>Solution of the problem:</p><pre>/**<br> * Definition for singly-linked list.<br> * function ListNode(val, next) {<br> * this.val = (val===undefined ? 0 : val)<br> * this.next = (next===undefined ? null : next)<br> * }<br> */<br>/**<br> * @param {ListNode} head<br> * @return {ListNode}<br> */<br>const reverList = function(head){<br> let prev = null;<br> let curr = head;<br> let next = null;<br>while(curr!=null){<br> next = curr.next;<br> curr.next = prev;<br> prev = curr;<br> curr = next;<br> }<br>return prev;<br>}<br>var removeNodes = function(head) {<br> // reverse list<br> let reversList = reverList(head);<br> <br> let maxNode = reversList;<br> let prevNode = reversList;<br> let currNode = reversList.next;<br> // removed list<br> while(currNode != null){<br> if(maxNode.val &gt; currNode.val){<br> currNode = currNode.next;<br> }else{<br> maxNode = currNode;<br> prevNode.next = currNode;<br> prevNode = prevNode.next;<br> currNode = currNode.next;<br> }<br> }<br>prevNode.next = null;<br> // reverse list<br> return reverList(reversList);<br>};</pre><p>If you have any query or suggestions leave your expression👨🏿‍💻🙌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50834cbe8c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Recursion Is the Most Elegant Trick in Programming]]></title>
            <link>https://medium.com/@ramnayan699/why-recursion-is-the-most-elegant-trick-in-programming-e259141dd0a8?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/e259141dd0a8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Fri, 29 May 2026 09:40:38 GMT</pubDate>
            <atom:updated>2026-05-29T09:56:02.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E2CdO_hpr2op-Hbw.png" /></figure><p><strong><em>To understand recursion, you must first understand recursion, </em></strong>in this i will explain about the recursion and resources where you can deep into dive.</p><p>Recursion is a concept of programming where an function call itself again and again till the base condition become false/break. recursion breaks down the bigger problem into small tasks so problem become easy to solve. let’s take and example and understand.</p><p>For something simple to start with — let’s write a function pow(x, n) that raises x to a natural power of n. In other words, multiplies x by itself n times.</p><pre>pow(2, 2) = 4<br>pow(2, 3) = 8<br>pow(2, 4) = 16</pre><p>This problem can be implemented in two way.</p><p><strong>Loop</strong>: Iterative thinking: the for/while loop</p><pre><br>function Pow(x,n){<br>  let result = 1;<br>  <br>  for(let i=0;i&lt;n;i++)<br>      result*=x;<br>  <br>  return result;<br>}<br><br>console.log(Pow(2,4));<br></pre><p><strong>Recursive thinking</strong>: simplify the task and call self</p><pre>function Pow(x,n){<br>  if(n === 1) {<br>      return x;<br>  }else {<br>    return x*Pow(x,n-1);<br>  }<br>}<br>console.log(Pow(2,4));</pre><ol><li>If n == 1, then everything is trivial. It is called <em>the base</em> of recursion, because it immediately produces the obvious result: pow(x, 1) equals x.</li><li>Otherwise, we can represent pow(x, n) as x * pow(x, n - 1). In maths, one would write xn = x * xn-1. This is called <em>a recursive step</em>: we transform the task into a simpler action (multiplication by x) and a simpler call of the same task (pow with lower n). Next steps simplify it further and further until n reaches 1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVKTEsF-Iz3SwgelxhD5EA.png" /></figure><p>We can also say that pow <em>recursively calls itself</em> till n == 1.</p><p>For example, to calculate pow(2, 4) the recursive variant does these steps:</p><ol><li>pow(2, 4) = 2 * pow(2, 3)</li><li>pow(2, 3) = 2 * pow(2, 2)</li><li>pow(2, 2) = 2 * pow(2, 1)</li><li>pow(2, 1) = 2</li></ol><p><strong>Flow of execution</strong>:</p><p>pow(2, 4)<br> └── 2 * pow(2, 3)<br> └── 2 * pow(2, 2)<br> └── 2 * pow(2, 1)<br> └── 2 ← base case (n=1)<br> └── 2 * 2 = 4<br> └── 2 * 4 = 8<br> └── 2 * 8 = 16 ✅</p><p>So, the recursion reduces a function call to a simpler one, and then — to even more simpler, and so on, until the result becomes obvious.</p><p><strong>Recursion is usually shorter</strong></p><p>A recursive solution is usually shorter than an iterative one.</p><p>Here we can rewrite the same using the conditional operator ? instead of if to make pow(x, n) more terse and still very readable:</p><pre>function pow(x, n) {<br>  return (n == 1) ? x : (x * pow(x, n - 1));<br>}</pre><p>Let’s see what happens during the pow(2, 3) call.</p><h3><a href="https://javascript.info/recursion#pow-2-3">pow(2, 3)</a></h3><p>In the beginning of the call pow(2, 3) the execution context will store variables: x = 2, n = 3, the execution flow is at line 1 of the function.</p><p>We can sketch it as:</p><ul><li><strong>Context: { x: 2, n: 3, at line 1 } pow(2, 3)</strong></li></ul><p>That’s when the function starts to execute. The condition n == 1 is falsy, so the flow continues into the second branch of if:</p><pre>function pow(x, n) {<br>  if (n == 1) {<br>    return x;<br>  } else {<br>    return x * pow(x, n - 1);<br>  }<br>}<br><br>alert( pow(2, 3) );</pre><p>The variables are same, but the line changes, so the context is now:</p><ul><li><strong>Context: { x: 2, n: 3, at line 5 } pow(2, 3)</strong></li></ul><p>To calculate x * pow(x, n - 1), we need to make a subcall of pow with new arguments pow(2, 2).</p><h3><a href="https://javascript.info/recursion#pow-2-2">pow(2, 2)</a></h3><p>To do a nested call, JavaScript remembers the current execution context in the <em>execution context stack</em>.</p><p>Here we call the same function pow, but it absolutely doesn’t matter. The process is the same for all functions:</p><ol><li>The current context is “remembered” on top of the stack.</li><li>The new context is created for the subcall.</li><li>When the subcall is finished — the previous context is popped from the stack, and its execution continues.</li></ol><p>Here’s the context stack when we entered the subcall pow(2, 2):</p><ul><li><strong>Context: { x: 2, n: 2, at line 1 } pow(2, 2)</strong></li><li>Context: { x: 2, n: 3, at line 5 } pow(2, 3)</li></ul><p>The new current execution context is on top (and bold), and previous remembered contexts are below.</p><p>When we finish the subcall — it is easy to resume the previous context, because it keeps both variables and the exact place of the code where it stopped.</p><p><strong>Please note:</strong></p><p>Here in the picture we use the word “line”, as in our example there’s only one subcall in line, but generally a single line of code may contain multiple subcalls, like pow(…) + pow(…) + somethingElse(…).</p><p>So it would be more precise to say that the execution resumes “immediately after the subcall”.</p><h3><a href="https://javascript.info/recursion#pow-2-1">pow(2, 1)</a></h3><p>The process repeats: a new subcall is made at line 5, now with arguments x=2, n=1.</p><p>A new execution context is created, the previous one is pushed on top of the stack:</p><ul><li><strong>Context: { x: 2, n: 1, at line 1 } pow(2, 1)</strong></li><li>Context: { x: 2, n: 2, at line 5 } pow(2, 2)</li><li>Context: { x: 2, n: 3, at line 5 } pow(2, 3)</li></ul><p>There are 2 old contexts now and 1 currently running for pow(2, 1).</p><h3><a href="https://javascript.info/recursion#the-exit">The exit</a></h3><p>During the execution of pow(2, 1), unlike before, the condition n == 1 is truthy, so the first branch of if works:</p><pre>function pow(x, n) {<br>  if (n == 1) {<br>    return x;<br>  } else {<br>    return x * pow(x, n - 1);<br>  }<br>}</pre><p>There are no more nested calls, so the function finishes, returning 2.</p><p>if you want to more resource for dive into deep please read the <a href="https://javascript.info/recursion#the-execution-context-and-stack"><em>blog</em></a><em> &amp; </em><a href="https://www.geeksforgeeks.org/dsa/introduction-to-recursion-2/"><em>gfg</em></a><em>. </em>if you like this please leave your impression🙌👨🏼‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e259141dd0a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[prev, curr, next — The Three Pointers That Reverse a Linked List]]></title>
            <link>https://medium.com/@ramnayan699/prev-curr-next-the-three-pointers-that-reverse-a-linked-list-54c88ac151d0?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/54c88ac151d0</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Tue, 26 May 2026 15:22:50 GMT</pubDate>
            <atom:updated>2026-05-26T15:24:21.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuCFiAoQ9OnRPqHo99lviw.png" /></figure><p>Single linked list a famous problem is: reverse linked list. before moving to explanation of problem let’s understand the single link list introduction.</p><p><strong>Single Linked List</strong>: A singly linked list is a linear data structure consisting of a sequence of objects called nodes. Instead of being stored in contiguous memory blocks, each node contains its own data and a reference (or pointer) pointing to the next node in the sequence.</p><p><strong>Core Components of a Node:</strong></p><p>Each individual <strong>Node</strong> in a singly linked list has two primary fields:</p><ul><li><strong>Data</strong>: Stores the actual value, object, or information (e.g., an integer or a string).</li><li><strong>Next Pointer</strong>: Stores the memory address of the next node in the sequence. The last node’s next pointer is set to null to mark the end of the list.</li></ul><p><strong>Memory Allocation:</strong></p><ul><li><strong>Dynamic Sizing</strong>: The list can grow or shrink in size dynamically at runtime.</li><li><strong>Fast Manipulations</strong>: Inserting or deleting elements only requires updating the memory references (pointers), making it highly efficient compared to shifting entire arrays.</li></ul><p>I hope you have understand the fundamental of Single linked list, if you want more explore you can follow the <a href="https://www.geeksforgeeks.org/dsa/singly-linked-list-tutorial/"><em>gfg</em></a> or <a href="https://takeuforward.org/linked-list/linked-list-introduction">takeuforward</a> blog post.</p><p><strong>Problem Statement</strong>: We have given an linked list which contain the numbers we have to reverse the list.</p><pre>Given the head of a singly linked list, reverse the list, and return the reversed list.<br><br>Example 1:<br>Input: head = [1,2,3,4,5]<br>Output: [5,4,3,2,1]</pre><p>Psuedo<strong> code:</strong></p><pre>head=[1,2,3,4,5];<br>curr = head;<br>prev = null;<br>nxt = null;<br><br>while(cur != null)<br>   nxt = curr.next;<br>   curr.prev = prev;<br>   prev = curr;<br>   curr = nxt;<br><br>return prev;</pre><p>I hope this psuedo code help to understand the problem, if you have any query leave your comment👨🏿‍💻🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54c88ac151d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dummy Node Trick — The Clean Way to Merge Two Sorted Lists]]></title>
            <link>https://medium.com/@ramnayan699/dummy-node-trick-the-clean-way-to-merge-two-sorted-lists-9aa68a0eaeca?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa68a0eaeca</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Mon, 25 May 2026 16:38:44 GMT</pubDate>
            <atom:updated>2026-05-25T16:38:44.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uKg-vHgZNN54xkim" /></figure><p>Today i went through the Leetcode Famous linked list problem was : <a href="https://leetcode.com/problems/merge-k-sorted-lists/"><strong><em>23. Merge k Sorted Lists</em></strong></a><strong><em>. </em></strong><em>So when i started to solve this i was blank how to manage K lists.</em></p><p>I found a hint from the problem : <a href="https://leetcode.com/problems/merge-two-sorted-lists/"><strong>21. Merge Two Sorted Lists</strong></a><strong>. </strong>which i had already solved before. In this post i’ll explain this problem line by line.</p><p>let’s take an example and understand this.</p><pre>Problem statement:<br><br>You are given the heads of two sorted linked lists list1 and list2.<br>Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.<br>Return the head of the merged linked list.<br><br>Example 1:<br><br>Input: list1 = [1,2,4], list2 = [1,3,4]<br>Output: [1,1,2,3,4,4]<br><br>Constraints:<br><br>The number of nodes in both lists is in the range [0, 50].<br>-100 &lt;= Node.val &lt;= 100<br>Both list1 and list2 are sorted in non-decreasing order.</pre><p>As you can see above example two list given we have to merge them into single list in sorted order. I’ll use the simplest approach to solve this by comparing from start of the both lists.</p><p>Psuedo code:</p><pre>temp = new Node(0);<br>node = temp;<br><br>   loop list1!=null &amp;&amp; list2!=null<br>      if list1[i].value &gt;= list2[i].value<br>          temp.next = list2[i];<br>          list2=list.next<br>       lese<br>          temp.next = list1[i]<br>          list1=list1.next;<br>    temp=temp.next;<br><br>// if list have different size/length<br>if list1!=null<br>  temp.next=list1;<br>else temp.next=list2;<br><br>//return node.next beacouse deafult value 0 added when node created.<br>return node.next;<br></pre><p>I hope you have understand the problem and approch how to fix it. if you wanna more reference please find the attached references from <a href="https://www.geeksforgeeks.org/dsa/merge-two-sorted-linked-lists/"><em>geeksforgeeks</em></a><em> and I</em><a href="https://www.interviewbit.com/problems/merge-two-sorted-lists/"><em>nterviewBit</em></a><em> etc.</em></p><p>I have used the anthropic to exaplain/visulaize this problem line-by line.</p><h3>Line by Line Explanation</h3><h3>Line 1</h3><blockquote><strong><em>“You are given the heads of two sorted linked lists list1 and list2.”</em></strong></blockquote><p>You are not given the full array — you are given only the <strong>starting node (head)</strong> of each linked list. Each list is already sorted in order.</p><pre>list1:  1 → 2 → 4 → null<br>        ↑<br>       head  (this is what you receive)</pre><pre>list2:  1 → 3 → 4 → null<br>        ↑<br>       head</pre><h3>Line 2</h3><blockquote><strong><em>“Merge the two lists into one sorted list.”</em></strong></blockquote><p>Combine both lists so the final result is a <strong>single sorted linked list</strong> containing all elements from both.</p><pre>list1:  1 → 2 → 4<br>list2:  1 → 3 → 4</pre><pre>merged: 1 → 1 → 2 → 3 → 4 → 4</pre><h3>Line 3</h3><blockquote><strong><em>“The list should be made by splicing together the nodes of the first two lists.”</em></strong></blockquote><p>This is the <strong>key constraint</strong> — do not create new nodes. Instead <strong>reuse and relink</strong> the existing nodes from list1 and list2 by changing their next pointers.</p><pre>❌ Wrong approach — creating new nodes<br>   new Node(1) → new Node(1) → new Node(2) ...</pre><pre>✅ Right approach — relinking existing nodes<br>   point list1&#39;s node.next or list2&#39;s node.next to each other</pre><h3>Line 4</h3><blockquote><strong><em>“Return the head of the merged linked list.”</em></strong></blockquote><p>After merging, return only the <strong>first node</strong> of the final merged list. The interviewer can traverse from there to see the full result.</p><pre>merged: 1 → 1 → 2 → 3 → 4 → 4 → null<br>        ↑<br>     return this</pre><h3>Example Walkthrough</h3><blockquote><strong><em>list1 = [1,2,4], </em></strong><strong><em>list2 = [1,3,4] → Output: </em></strong><strong><em>[1,1,2,3,4,4]</em></strong><em>---</em></blockquote><h3>Constraint — [0, 50] nodes, values [-100, 100]</h3><pre>The number of nodes is in range [0, 50]<br>→ either list can be EMPTY (length 0) — handle null check!</pre><pre>-100 &lt;= Node.val &lt;= 100<br>→ values can be negative — comparison still works normally</pre><h3>Key Points to Remember</h3><p>Line What it Means “heads of two sorted lists” You only get the first node, not the full array “merge into one sorted list” Final output must be sorted end to end “splicing together nodes” Reuse existing nodes, don’t create new ones “return the head” Return only the first node of the merged result</p><h3>One Line Summary</h3><blockquote><em>At each step </em><strong><em>compare the front nodes</em></strong><em> of both lists, </em><strong><em>attach the smaller one</em></strong><em> to your result, and </em><strong><em>advance that pointer</em></strong><em> — until one list runs out, then </em><strong><em>attach the remainder</em></strong><em> of the other.</em></blockquote><p>If you found this useful and informative, you can leave your impressions for motivation and improvement 🙌👨🏿‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa68a0eaeca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Cycle Detection is the Secret to Sorting Permutations Optimally]]></title>
            <link>https://medium.com/@ramnayan699/minimum-operations-to-sort-a-permutation-bc74d5c3e1d8?source=rss-c51f36d38b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc74d5c3e1d8</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ramnayan Yadav]]></dc:creator>
            <pubDate>Sun, 24 May 2026 12:31:51 GMT</pubDate>
            <atom:updated>2026-05-24T12:43:06.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zDhS7xat4aXe29zm" /><figcaption>Photo by <a href="https://unsplash.com/@throughjackseyes?utm_source=medium&amp;utm_medium=referral">Jack French</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A permutation is an array containing each number from <strong>1 to n exactly once</strong>, just arranged in a different order.</p><pre>[2, 3, 1, 4]  ✅ valid permutation of [1, 2, 3, 4]<br>[1, 3, 3, 4]  ❌ not a permutation (3 appears twice)</pre><h3>What is the Problem?</h3><p>Given a permutation array, find the <strong>minimum number of swaps</strong> required to sort it in ascending order.</p><pre>Input:  [2, 3, 1, 4]<br>Output: 2</pre><pre>Input:  [4, 3, 2, 1]<br>Output: 2</pre><h3>Approach 1 — Brute Force O(n²)</h3><p>The naive approach is to use <strong>selection sort</strong> — find the minimum element and swap it to the correct position.</p><pre>function minSwapsBrute(arr) {<br>    let swaps = 0;<br>    let n = arr.length;<br>    for (let i = 0; i &lt; n; i++) {<br>        if (arr[i] !== i + 1) {<br>            // find correct element and swap<br>            let j = i + 1;<br>            while (arr[j] !== i + 1) j++;<br>            [arr[i], arr[j]] = [arr[j], arr[i]];<br>            swaps++;<br>        }<br>    }<br>    return swaps;<br>}</pre><p><strong>Problem:</strong> This is O(n²) — too slow for large inputs. We need something smarter.</p><h3>Approach 2 — Cycle Detection O(n)</h3><p>This is the <strong>optimal approach</strong>. The core idea comes from graph theory.</p><h3>💡 Key Insight</h3><blockquote><em>Every permutation can be broken down into </em><strong><em>independent cycles</em></strong><em>. Each cycle of length </em><em>k requires exactly </em><em>k - 1 swaps to sort.</em></blockquote><p>So the formula is:</p><pre>total swaps = Σ (cycle_length - 1)<br>            = total_elements - total_cycles</pre><h3>What is a Cycle?</h3><p>Think of each element as a <strong>node</strong> and draw an arrow from position i to the position where arr[i] belongs.</p><p><strong>Example:</strong> arr = [2, 3, 1, 4]</p><pre>Position:  0    1    2    3<br>Value:     2    3    1    4<br>Target:    1    2    3    4</pre><pre>Mapping (0-indexed):<br>  index 0 has value 2 → should go to index 1<br>  index 1 has value 3 → should go to index 2<br>  index 2 has value 1 → should go to index 0<br>  index 3 has value 4 → already at index 3</pre><p>Drawing arrows:</p><pre>0 → 1 → 2 → 0   (cycle of length 3)<br>3 → 3            (cycle of length 1, already sorted)</pre><h3>Visualizing Cycles Here is the cycle detection diagram. Then the algorithm and full solution follow.</h3><h3>How Cycle Detection Works — Step by Step</h3><p>For arr = [2, 3, 1, 4] (1-indexed values), converting to 0-indexed positions:</p><pre>Element 2 belongs at index 1  →  0 points to 1<br>Element 3 belongs at index 2  →  1 points to 2<br>Element 1 belongs at index 0  →  2 points to 0<br>Element 4 belongs at index 3  →  3 points to 3 (already correct)</pre><p>Traversing from index 0:</p><pre>0 → 1 → 2 → 0   CYCLE FOUND (length = 3, swaps = 2)<br>3 → 3            CYCLE FOUND (length = 1, swaps = 0)</pre><pre>Total swaps = 2 + 0 = 2</pre><h3>Full Solution in JavaScript</h3><pre><br>var minSwapsCycleDetection = function(arr) {<br>    let n = arr.length;<br>    let visited = new Array(n).fill(false);<br>    let totalSwaps = 0;<br>    for (let i = 0; i &lt; n; i++) {<br>        // Skip if already visited or already in correct position<br>        if (visited[i] || arr[i] === i + 1) {<br>            visited[i] = true;<br>            continue;<br>        }<br>        // Traverse the cycle starting from index i<br>        let cycleLength = 0;<br>        let j = i;<br>        while (!visited[j]) {<br>            visited[j] = true;<br>            j = arr[j] - 1;   // move to where current element belongs<br>            cycleLength++;<br>        }<br>        // A cycle of length k needs k-1 swaps<br>        totalSwaps += cycleLength - 1;<br>    }<br>    return totalSwaps;<br>};</pre><h3>Dry Run — arr = [4, 3, 2, 1]</h3><pre>0-indexed mapping:<br>  arr[0]=4 → belongs at index 3  →  0→3<br>  arr[1]=3 → belongs at index 2  →  1→2<br>  arr[2]=2 → belongs at index 1  →  2→1<br>  arr[3]=1 → belongs at index 0  →  3→0</pre><pre>Cycle traversal:<br>  Start at 0 → 3 → 0   cycle length = 2, swaps = 1<br>  Start at 1 → 2 → 1   cycle length = 2, swaps = 1</pre><pre>Total swaps = 1 + 1 = 2 ✅</pre><h3>Complexity</h3><p>Value Reason Time O(n) Each element visited exactly once Space O(n) Visited array of size n</p><h3>Key Formula</h3><pre>total swaps = Σ (cycle_length - 1)<br>            = (total elements) - (total number of cycles)</pre><p>A cycle of length 1 means the element is already in its correct position — zero swaps needed. The longer the cycle, the more swaps required to untangle it.</p><h3>Real World Connection</h3><blockquote><em>Inversion count measures “how unsorted” an array is. Minimum swaps to sort measures “how much work is needed to fix it.” Both problems share the same Merge Sort and Cycle Detection roots — master these two and a whole family of problems opens up.</em></blockquote><p>If you want to explore further, check out these related problems — <a href="https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/">Minimum Swaps to Sort</a>, <a href="https://leetcode.com/problems/sort-colors/">Sort Colors</a>, and <a href="https://leetcode.com/problems/couples-holding-hands/">Couples Holding Hands</a> — they all share the same cycle decomposition idea at heart.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc74d5c3e1d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>