Skip to content

What is a Greedy Algorithm?

Patterns·6 min·Python code

Greedy algorithms build a solution one step at a time, taking the locally optimal choice and never undoing it. They reach the global optimum only when the problem has the greedy choice property and optimal substructure.

How a Greedy Algorithm Makes Locally Optimal Choices

Think of a cashier making change. Handing back the fewest coins means taking the largest coin that fits, again and again, without reconsidering an earlier choice.

That is the full shape of greedy. Order the options with sorting algorithms or a heap, then repeatedly grab the one that looks right now and commit to it, with no backtracking.

Greedy never revisits a decision, so the loop stays short. Hard part is knowing whether quick local wins add up to the optimal answer.

When a Greedy Algorithm Is Provably Correct

Greedy returns the true optimum only when two properties hold. Greedy choice property means a locally optimal choice can always lead to a global optimum. Optimal substructure means an optimal solution contains optimal solutions to its subproblems.

Interval scheduling, known as activity selection, is the textbook success. Sort by finish time and keep every meeting that starts after the last kept one ends, and you fit the most non overlapping meetings into one room.

Exchange arguments prove it, because swapping any other first meeting for the earliest finishing one never makes the schedule worse.

Same local choice logic underpins Huffman coding, Kruskal's and Prim's minimum spanning trees and Dijkstra's shortest paths.

When a Greedy Algorithm Gives the Wrong Answer

Greedy looks right on the small inputs you test and then fails on ones you did not. Making change is the classic trap.

With coins 1, 5, 10 and 25, the largest coin that fits is optimal. Change the set to 1, 3 and 4 and ask for 6, and greedy returns 4 + 1 + 1 (three coins) while 3 + 3 (two coins) wins.

When earlier choices constrain later ones like this, you need dynamic programming, which weighs combinations instead of committing to one. Never trust greedy until you back it with an exchange argument or find a counterexample.

Apply that test on CodeStory's greedy practice problems.

Greedy Algorithm Code Example in Python

pythonInterval scheduling in Python that keeps every meeting starting after the last kept one ends.

def max_meetings(intervals):
    # Greedy: repeatedly keep the meeting that finishes earliest.
    intervals.sort(key=lambda iv: iv[1])       # sort by finish time
    count, last_end = 0, float("-inf")
    for start, end in intervals:
        if start >= last_end:                  # no overlap with last meeting
            count += 1
            last_end = end                     # commit and never look back
    return count

# max_meetings([(1, 3), (2, 5), (4, 7), (6, 9)]) -> 3

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Greedy Algorithm Time and Space Complexity

TimeO(n log n) because the sort dominates and the greedy scan is one O(n) pass
SpaceO(1) extra beyond the input when sorting in place, otherwise O(n)

Cost stays the same for sorted and shuffled input, because the sort always happens. Heap based greedy algorithms like Dijkstra cost O((V + E) log V).

When to Use a Greedy Algorithm

  • Scheduling intervals or activities, where keeping the earliest finishing one fits the most meetings.
  • Optimisation problems where an exchange argument proves a locally optimal choice is safe.
  • Graph and encoding problems with provable local choices, like Dijkstra, Kruskal, Prim and Huffman coding.
  • Coin change or resource allocation when the cost structure is canonical, like standard currency.

Mistakes to Avoid

  • Assuming greedy is optimal without proof. Coins 1, 3 and 4 making 6 give greedy three coins when two coins win.
  • Choosing the wrong sort key, like sorting intervals by start time or shortest duration instead of earliest finish, which gives schedules that are not optimal.
  • Using greedy when subproblems overlap and choices interact, which needs dynamic programming instead of a one pass commit.

Greedy Algorithm FAQs

Is a greedy algorithm hard to learn?

Mechanics are short. Order the options, then loop once taking the locally optimal choice. Proving that choice correct is the hard part, and an exchange argument is the tool for it.

When should I use a greedy algorithm instead of dynamic programming?

Use greedy when you can prove the greedy choice property with an exchange argument. If earlier choices constrain later ones, like coin change with odd denominations, use dynamic programming. Greedy costs less code and time, so try to prove it first.

What is the time complexity of a greedy algorithm?

Most greedy algorithms cost O(n log n) because of an initial sort or priority queue, with O(1) to O(n) extra space. Greedy scans take one O(n) pass. Heap based versions like Dijkstra's shortest paths cost O((V + E) log V).

Why does greedy fail for coin change?

Greedy takes the largest coin that fits, which can strand you. With coins 1, 3 and 4 making 6, greedy gives 4 + 1 + 1 while 3 + 3 uses fewer coins. Standard currencies are built so greedy works, and arbitrary coin sets need dynamic programming.

What is the greedy choice property?

Problems have it when some locally optimal first choice always belongs to a global optimum. Interval scheduling has it, because the earliest finishing meeting never hurts the schedule.

Which problems use a greedy algorithm?

Interval scheduling, Huffman coding, Kruskal's and Prim's minimum spanning trees and Dijkstra's shortest paths all use greedy choices.

How do I practise greedy algorithms on CodeStory?

Work through CodeStory's greedy practice problems and test every choice with an exchange argument or a counterexample.

Related Guides

Guides are step one. In a CodeStory batch you code the greedy choice yourself, then defend it in a scored mock round.

Talk to a Mentor

Stuck on Greedy Algorithms? Get a Free Callback

Tell CodeStory which greedy choice confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first greedy choice to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.