Why Greedy Works and When It Fails in DSA Typescript - Performance Analysis
We want to understand how fast greedy algorithms run and why their speed depends on the problem.
When does greedy give a quick solution, and when does it take longer or fail?
Analyze the time complexity of this simple greedy approach to the coin change problem.
function greedyCoinChange(coins: number[], amount: number): number {
let count = 0;
for (let i = coins.length - 1; i >= 0; i--) {
while (amount >= coins[i]) {
amount -= coins[i];
count++;
}
}
return count;
}
This code tries to use the largest coin first repeatedly until the amount is covered or no coins left.
Look at the loops and repeated steps:
- Primary operation: The inner while loop subtracting coins from amount.
- How many times: Up to amount divided by the smallest coin value.
As the amount grows, the number of subtractions grows roughly proportional to amount.
| Input Size (amount) | Approx. Operations |
|---|---|
| 10 | About 10 subtractions |
| 100 | About 100 subtractions |
| 1000 | About 1000 subtractions |
Pattern observation: The work grows roughly linearly with the amount size.
Time Complexity: O(n + m)
This means the time grows with the number of coin types (n) plus the amount (m), because the outer loop is O(n) and total inner iterations are O(m).
[X] Wrong: "Greedy always finds the best answer quickly for any problem."
[OK] Correct: Greedy works fast but can fail to find the best answer if the problem needs looking ahead or combining choices differently.
Understanding when greedy works helps you pick the right tool and explain your choices clearly in interviews.
"What if the coin denominations were not sorted or included tricky values? How would that affect the time complexity and correctness?"