<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged greedy</title>
<link>https://coderlegion.com/tag/greedy</link>
<description>Powered by Question2Answer</description>
<item>
<title>Demystifying Greedy Algorithms: How Local Choices Solve Global Problems in Node.js</title>
<link>https://coderlegion.com/31180/demystifying-greedy-algorithms-how-local-choices-solve-global-problems-in-node-js</link>
<description>&lt;h3 id=&quot;what-is-a-greedy-algorithm-&quot;&gt;What is a Greedy Algorithm?&lt;/h3&gt;
&lt;p&gt;A greedy algorithm is an algorithmic strategy that solves a problem by making the most optimal decision at each individual step. Instead of looking ahead to long-term consequences or evaluating every possible combination, it focuses exclusively on immediate, short-term gain. If local choices logically compound into the ideal final result, the greedy strategy succeeds with maximum computational efficiency.&lt;/p&gt;
&lt;h3 id=&quot;the-cashier-s-coin-trick&quot;&gt;The Cashier’s Coin Trick&lt;/h3&gt;
&lt;p&gt;Imagine you are a cashier at a grocery store, and you need to give a customer 41 cents in change using the fewest coins possible. You look at your cash register, which contains quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢).&lt;/p&gt;
&lt;p&gt;Instead of calculating every conceivable combination of coins, you naturally make the &quot;greedy&quot; choice at each step:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Grab the largest coin that does not exceed 41 cents: a Quarter (25¢). You now owe 16 cents.&lt;/li&gt;
&lt;li&gt;Grab the largest coin that does not exceed 16 cents: a Dime (10¢). You now owe 6 cents.&lt;/li&gt;
&lt;li&gt;Grab the largest coin that does not exceed 6 cents: a Nickel (5¢). You now owe 1 cent.&lt;/li&gt;
&lt;li&gt;Grab the largest coin that does not exceed 1 cent: a Penny (1¢). You now owe 0 cents.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;You solved the problem instantly by picking the biggest immediate payoff at every step. That is precisely how a greedy algorithm operates in software.&lt;/p&gt;
&lt;h3 id=&quot;why-greedy-algorithms-matter-in-tech&quot;&gt;Why Greedy Algorithms Matter in Tech&lt;/h3&gt;
&lt;p&gt;In software engineering, computing the mathematically perfect solution for massive datasets can sometimes take hours—or even years—if an application tries to test every possible outcome. Software developers intentionally use greedy algorithms when a guaranteed quick answer that is optimal saves massive amounts of CPU memory and processing time.&lt;/p&gt;
&lt;p&gt;For instance, network routing protocols use greedy choices to route internet data packets along the shortest immediate paths between routers. Database query engines, file compression utilities like ZIP tools, and job schedulers in operating systems all rely on greedy strategies to keep web software responsive and performant under heavy traffic loads.&lt;/p&gt;
&lt;h3 id=&quot;code-example-making-change-in-node-js&quot;&gt;Code Example: Making Change in Node.js&lt;/h3&gt;
&lt;p&gt;Here is a plain Node.js implementation showing how a greedy approach quickly calculates coin change for any given amount:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;// Function to give change using the minimum number of coins
function makeChange(amount, coins = [25, 10, 5, 1]) {
  const result = {};
  let remaining = amount;

  // Iterate through available coins sorted from highest to lowest
  for (const coin of coins) {
    if (remaining &amp;lt;= 0) break;

    // Calculate how many coins of this denomination fit
    const count = Math.floor(remaining / coin);
    if (count &amp;gt; 0) {
      result[`${coin}c`] = count;
      remaining -= count * coin;
    }
  }

  return result;
}

// Example usage: Change for 87 cents
const change = makeChange(87);
console.log('Change breakdown:', change);
// Output: Change breakdown: { '25c': 3, '10c': 1, '1c': 2 }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this code, the algorithm loops through sorted coin values and takes as many of the highest denomination as possible before moving to smaller coins.&lt;/p&gt;
&lt;h3 id=&quot;the-takeaway&quot;&gt;The Takeaway&lt;/h3&gt;
&lt;p&gt;Greedy algorithms trade exhaustive foresight for immediate speed, proving that making the best local decision at every step can often yield the best global outcome. While they do not work for every single problem—especially when early sacrifices yield better long-term rewards—understanding when to apply a greedy strategy is a fundamental skill for building high-performance backend systems.&lt;/p&gt;
&lt;hr&gt;
&lt;p align=&quot;center&quot;&gt;
  &lt;a href=&quot;https://www.buymeacoffee.com/saurav_tb_pandey&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer nofollow&quot;&gt;
    &lt;img src=&quot;https://img.shields.io/badge/Buy_Me_A_Coffee-FFDD00?style=for-the-badge&amp;amp;logo=buy-me-a-coffee&amp;amp;logoColor=black&quot; alt=&quot;Buy Me A Coffee&quot;&gt;
&lt;p&gt;  &lt;/p&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Enjoyed this breakdown? Support my open-source work on &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.buymeacoffee.com/saurav_tb_pandey&quot;&gt;Buy Me a Coffee&lt;/a&gt; or explore &lt;a rel=&quot;nofollow&quot; href=&quot;https://www.npmjs.com/package/react-hook-lab&quot;&gt;react-hook-lab&lt;/a&gt;!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Originally published on my blog. You can &lt;a rel=&quot;nofollow&quot; href=&quot;https://sauravtbpandey.blogspot.com/2026/10/understanding-greedy-algorithms-simple.html&quot;&gt;read the alternative breakdown here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/31180/demystifying-greedy-algorithms-how-local-choices-solve-global-problems-in-node-js</guid>
<pubDate>Thu, 15 Oct 2026 08:35:56 +0000</pubDate>
</item>
<item>
<title>Leetcode #324. Wiggle Sort II</title>
<link>https://coderlegion.com/24112/leetcode-324-wiggle-sort-ii</link>
<description>&lt;p&gt;&lt;em&gt;Greedy algorithms are usually given in leetcode style technical interviews.They involve taking the maximum or minimum.Below is a an example of using the greedy approach to solve a problem.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Given an integer array nums, reorder it such that nums[0] &amp;lt; nums[1] &amp;gt; nums[2] &amp;lt; nums[3]....&lt;/p&gt;
&lt;p&gt;You may assume the input array always has a valid answer.&lt;/p&gt;
&lt;p&gt;Example 1:&lt;/p&gt;
&lt;p&gt;Input: nums = [1,5,1,1,6,4]&lt;br&gt;
Output: [1,6,1,5,1,4]&lt;br&gt;
Explanation: [1,4,1,5,1,6] is also accepted.&lt;br&gt;
Example 2:&lt;/p&gt;
&lt;p&gt;Input: nums = [1,3,2,2,3,1]&lt;br&gt;
Output: [2,3,1,3,1,2]&lt;/p&gt;
&lt;p&gt;Constraints:&lt;/p&gt;
&lt;p&gt;.1 &amp;lt;= nums.length &amp;lt;= 5 * 104&lt;br&gt;
.0 &amp;lt;= nums[i] &amp;lt;= 5000&lt;br&gt;
.It is guaranteed that there will be an answer for the given input nums.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Discussion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This algorithm can be solved using the greedy approach.We copy the contents of the original array into a new one and sort it.We create two pointers. One is placed at the end of the new array,the other in the middle of it.We iterate through the original from the start.If the index is even,we take the value from the second pointer.Otherwise,we take the value from the first one.This ensures that the biggest values are always placed at the odd indexes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Java&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Solution {
    public void wiggleSort(int[] nums) {
     int [] nums1= new int [nums.length];
     for(int i=0;i&amp;lt;nums.length;i++)nums1[i]=nums[i];
     Arrays.sort(nums1);
     int nums1Index=nums.length-1;
     int nums1Index1=(nums.length-1)/2;      
     for(int i=0;i&amp;lt;nums.length;i++){
      if(i%2==0)nums[i]=nums1[nums1Index1--];
      else nums[i]=nums1[nums1Index--];  
     }
     return;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C#&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Solution {
    public void WiggleSort(int[] nums) {
     int [] nums1= new int [nums.Length];
     for(int i=0;i&amp;lt;nums.Length;i++)nums1[i]=nums[i];
     Array.Sort(nums1);
     int nums1Index=nums.Length-1;
     int nums1Index1=(nums.Length-1)/2;      
     for(int i=0;i&amp;lt;nums.Length;i++){
      if(i%2==0)nums[i]=nums1[nums1Index1--];
      else nums[i]=nums1[nums1Index--];  
     }
     return;   
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;C++&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Solution {
public:
    void wiggleSort(vector&amp;lt;int&amp;gt;&amp;amp; nums) {
     vector&amp;lt;int&amp;gt; nums1;
     for(int i=0;i&amp;lt;nums.size();i++)nums1.push_back(nums[i]);
     std::sort(nums1.begin(),nums1.end());
     int nums1Index=nums.size()-1;
     int nums1Index1=(nums.size()-1)/2;      
     for(int i=0;i&amp;lt;nums.size();i++){
      if(i%2==0)nums[i]=nums1[nums1Index1--];
      else nums[i]=nums1[nums1Index--];  
     }
     return;   
    }
};
&lt;/code&gt;&lt;/pre&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/24112/leetcode-324-wiggle-sort-ii</guid>
<pubDate>Tue, 04 Aug 2026 19:55:27 +0000</pubDate>
</item>
</channel>
</rss>