What is a Greedy Algorithm?
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.
The Cashier’s Coin Trick
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¢).
Instead of calculating every conceivable combination of coins, you naturally make the "greedy" choice at each step:
- Grab the largest coin that does not exceed 41 cents: a Quarter (25¢). You now owe 16 cents.
- Grab the largest coin that does not exceed 16 cents: a Dime (10¢). You now owe 6 cents.
- Grab the largest coin that does not exceed 6 cents: a Nickel (5¢). You now owe 1 cent.
- Grab the largest coin that does not exceed 1 cent: a Penny (1¢). You now owe 0 cents.
You solved the problem instantly by picking the biggest immediate payoff at every step. That is precisely how a greedy algorithm operates in software.
Why Greedy Algorithms Matter in Tech
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.
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.
Code Example: Making Change in Node.js
Here is a plain Node.js implementation showing how a greedy approach quickly calculates coin change for any given amount:
// 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 <= 0) break;
// Calculate how many coins of this denomination fit
const count = Math.floor(remaining / coin);
if (count > 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 }
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.
The Takeaway
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.
Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!
Originally published on my blog. You can read the alternative breakdown here.
Top comments (0)