← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Greedy Algorithms

Algorithms PHP 5.0+ Intermediate
debt(d9/e7/b5/t7)
d9 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'silent in production until users hit it' (d9). The detection_hints field explicitly states 'automated: no' and describes the pattern as a scheduling/resource allocation problem solved suboptimally. There is no static analysis tool that can detect when a greedy algorithm has been incorrectly applied to a problem that requires DP or backtracking — the code runs without errors, produces plausible-looking (but wrong) output, and the bug only surfaces when edge-case inputs expose the suboptimality, often in production or under specific data distributions.

e7 Effort Remediation debt — work required to fix once spotted

Closest to 'cross-cutting refactor across the codebase' (e7). The quick_fix states the fix requires verifying the greedy choice property and switching to dynamic programming when subproblems overlap. Replacing a greedy solution with DP is not a one-line patch — it requires redesigning the algorithm, introducing memoization or tabulation structures, and often rethinking data flow. If the greedy approach was used as a shared utility or embedded in multiple scheduling/allocation components, the rework crosses multiple files and logic boundaries, placing it at e7.

b5 Burden Structural debt — long-term weight of choosing wrong

Closest to 'persistent productivity tax' (b5). The applies_to covers both web and cli contexts broadly. A greedy algorithm embedded in a core optimisation routine imposes ongoing burden: future maintainers must understand why the approach was chosen, whether it's correct for new input shapes, and face the risk of silent regressions when problem constraints change. It's not system-defining (b9) but does slow down multiple work streams when the algorithm is load-bearing in scheduling or resource allocation logic.

t7 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'serious trap — contradicts how a similar concept works elsewhere' (t7). The misconception field explicitly states the canonical wrong belief: 'Greedy algorithms always find the optimal solution.' This is a well-documented but serious trap — competent developers familiar with dynamic programming often assume greedy is a valid shortcut for problems like the general knapsack or arbitrary-denomination coin change, where it silently produces wrong answers. The trap is compounded by the fact that greedy IS correct for superficially similar problems (e.g. standard coin systems, activity selection), making the boundary non-obvious and the wrong assumption highly plausible.

About DEBT scoring →

Also Known As

greedy choice local optimum

TL;DR

Algorithms that make the locally optimal choice at each step — fast and simple, but only produce the globally optimal solution for problems with the greedy choice property.

Explanation

A greedy algorithm selects the best available option at each step without reconsidering previous choices. It works when: the greedy choice is safe (local optimum leads to global optimum) and the problem has optimal substructure. Classic examples: coin change (if denominations allow), interval scheduling (sort by end time), Huffman coding, Kruskal/Prim for minimum spanning trees. Fails for: general coin change (e.g. coins {1,3,4} — greedy for 6 gives {4,1,1} not optimal {3,3}).

Diagram

flowchart TD
    PROBLEM[Optimisation problem] --> CHOICE[Make locally optimal choice<br/>at each step]
    CHOICE --> IRREV[Never reconsider<br/>irrevocable decision]
    IRREV --> NEXT[Move to next subproblem]
    NEXT -->|done?| SOLUTION[Global solution]
    subgraph Works For
        COIN[Coin change - large denominations first]
        HUFFMAN[Huffman coding]
        DIJKSTRA[Dijkstra shortest path]
        PRIM[Prim minimum spanning tree]
    end
    subgraph Does NOT Work For
        KNAPSACK[0-1 Knapsack - needs DP]
        TSP[Travelling Salesman]
    end
style SOLUTION fill:#238636,color:#fff
style KNAPSACK fill:#f85149,color:#fff
style TSP fill:#f85149,color:#fff

Common Misconception

Greedy algorithms always find the optimal solution — they only work when the greedy choice property holds; many problems (knapsack, TSP) require dynamic programming or backtracking.

Why It Matters

Greedy algorithms are O(n log n) or faster — recognising when a greedy approach is correct avoids the complexity of dynamic programming for problems that don't need it.

Common Mistakes

  • Applying greedy to problems where it doesn't hold — coin change with arbitrary denominations requires DP.
  • Not sorting before applying greedy — most greedy algorithms require the input in a specific order.
  • Confusing greedy with DP — if a problem has overlapping subproblems, DP is required; if choices are independent, greedy may work.
  • Not proving the greedy choice property — assuming greedy works without verifying leads to subtly wrong solutions.

Code Examples

✗ Vulnerable
// Greedy coin change fails for non-standard denominations:
function greedyChange(int $amount, array $coins): array {
    rsort($coins); // Sort descending
    $result = [];
    foreach ($coins as $coin) {
        while ($amount >= $coin) { $result[] = $coin; $amount -= $coin; }
    }
    return $result;
}
// greedyChange(6, [1,3,4]) returns [4,1,1] — 3 coins
// Optimal: [3,3] — 2 coins. Greedy fails here.
✓ Fixed
// DP coin change — always optimal:
function dpChange(int $amount, array $coins): int {
    $dp = array_fill(0, $amount + 1, PHP_INT_MAX);
    $dp[0] = 0;
    for ($i = 1; $i <= $amount; $i++) {
        foreach ($coins as $coin) {
            if ($coin <= $i && $dp[$i - $coin] !== PHP_INT_MAX) {
                $dp[$i] = min($dp[$i], $dp[$i - $coin] + 1);
            }
        }
    }
    return $dp[$amount] === PHP_INT_MAX ? -1 : $dp[$amount];
}

Added 15 Mar 2026
Edited 22 Mar 2026
Views 51
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 1 ping T 1 ping F 2 pings S 1 ping S 1 ping M 0 pings T 2 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 1 ping S 1 ping S 0 pings M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Perplexity 8 Amazonbot 7 Scrapy 6 Ahrefs 4 SEMrush 4 Google 3 Unknown AI 2 Claude 2 ChatGPT 2 Majestic 1 Bing 1 Meta AI 1 PetalBot 1
crawler 39 crawler_json 3
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Greedy works when a locally optimal choice always leads to a global optimum — verify this property before using greedy; use dynamic programming when subproblems overlap
📦 Applies To
PHP 5.0+ web cli
🔗 Prerequisites
🔍 Detection Hints
Scheduling optimisation or resource allocation problem solved suboptimally where greedy would be exact
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update


✓ schema.org compliant