close
The Wayback Machine - https://web.archive.org/web/20241206172105/https://www.geeksforgeeks.org/introduction-to-greedy-algorithm-data-structures-and-algorithm-tutorials/
Open In App

Greedy Algorithm Tutorial – Examples, Application and Practice Problem

Last Updated : 26 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. 

An optimization problem can be solved using Greedy if the problem has the following property: 

  • At every step, we can make a choice that looks best at the moment, and we get the optimal solution to the complete problem. 
  • Some popular Greedy Algorithms are Fractional Knapsack, Dijkstra’s algorithm, Kruskal’s algorithm, Huffman coding and Prim’s Algorithm
  • The greedy algorithms are sometimes also used to get an approximation for Hard optimization problems. For example, Traveling Salesman Problem is an NP-Hard problem. A Greedy choice for this problem is to pick the nearest unvisited city from the current city at every step. These solutions don’t always produce the best optimal solution but can be used to get an approximately optimal solution.

However, it’s important to note that not all problems are suitable for greedy algorithms. They work best when the problem exhibits the following properties:

  • Greedy Choice Property: The optimal solution can be constructed by making the best local choice at each step.
  • Optimal Substructure: The optimal solution to the problem contains the optimal solutions to its subproblems.

Characteristics of Greedy Algorithm

Here are the characteristics of a greedy algorithm:

  • Greedy algorithms are simple and easy to implement.
  • They are efficient in terms of time complexity, often providing quick solutions. Greedy Algorithms are typically preferred over Dynamic Programming for the problems where both are applied. For example, Jump Game problem and Single Source Shortest Path Problem (Dijkstra is preferred over Bellman Ford where we do not have negative weights)..
  • These algorithms do not reconsider previous choices, as they make decisions based on current information without looking ahead.

These characteristics help to define the nature and usage of greedy algorithms in problem-solving.

Want to master Greedy algorithm and more? Check out our DSA Self-Paced Course for a comprehensive guide to Data Structures and Algorithms at your own pace. This course will help you build a strong foundation and advance your problem-solving skills.

How does the Greedy Algorithm works?

Greedy Algorithm solve optimization problems by making the best local choice at each step in the hope of finding the global optimum. It’s like taking the best option available at each moment, hoping it will lead to the best overall outcome.

Here’s how it works:

  1. Start with the initial state of the problem. This is the starting point from where you begin making choices.
  2. Evaluate all possible choices you can make from the current state. Consider all the options available at that specific moment.
  3. Choose the option that seems best at that moment, regardless of future consequences. This is the “greedy” part – you take the best option available now, even if it might not be the best in the long run.
  4. Move to the new state based on your chosen option. This becomes your new starting point for the next iteration.
  5. Repeat steps 2-4 until you reach the goal state or no further progress is possible. Keep making the best local choices until you reach the end of the problem or get stuck..

Example:

Let’s say you have a set of coins with values {1, 2, 5, 10, 20, 50, 100} and you need to give minimum number of coin to someone change for 36 .

The greedy algorithm for making change would work as follows:

  1. Start with the largest coin value that is less than or equal to the amount to be changed. In this case, the largest coin less than 36 is 20 .
  2. Subtract the largest coin value from the amount to be changed, and add the coin to the solution. In this case, subtracting 20 from 36 gives 16 , and we add a 20 coin to the solution.
  3. Repeat steps 1 and 2 until the amount to be changed becomes 0.

So, using the greedy algorithm, the solution for making change for 36 would be one 20 coins, one 10 coin, one 5 coins and one 1 coin needed.

Note: This is just one example, and other greedy choices could have been made at each step. However, in this case, the greedy approach leads to the optimal solution.

The greedy algorithm is not always the optimal solution for every optimization problem, as shown in the example below.

Graph with weighted vertices

Graph with weighted vertices

  • In the above graph starting from the root node 10 if we greedily select the next node to obtain the most weighted path the next selected node will be 5 that will take the total sum to 15 and the path will end as there is no child of 5 but the path 10 -> 5 is not the maximum weight path.
BERJAYA

Greedy Approach fails

  • In order to find the most weighted path all possible path sum must be computed and their path sum must be compared to get the desired result, it is visible that the most weighted path in the above graph is 10 -> 1 -> 30 that gives the path sum 41 .
BERJAYA

Correct Approach

  • In such cases Greedy approach wouldn’t work instead complete paths from root to leaf node has to be considered to get the correct answer i.e. the most weighted path, This can be achieved by recursively checking all the paths and calculating their weight.

Greedy Algorithm Vs Dynamic Programming

Below are the comparison of Greedy Algorithm and Dynamic Programming based on various criteria:

Criteria Greedy Algorithm Dynamic Programming
Basic Idea Makes the locally optimal choice at each stage Solves subproblems and builds up to the optimal solution
Optimal Solution Not always guaranteed to provide the globally optimal solution Guarantees the globally optimal solution
Time Complexity Typically faster; often linear or polynomial time Usually slower due to solving overlapping subproblems
Space Complexity Requires less memory; often constant or linear space Requires more memory due to storing intermediate results
Subproblems Overlapping Does not handle overlapping subproblems Handles overlapping subproblems efficiently
Examples Finding minimum spanning tree, Huffman coding Matrix chain multiplication, shortest path problems
Applications Used when a greedy choice at each step leads to the globally optimal solution Applied when the problem can be broken down into overlapping subproblems

Applications of Greedy Algorithms:

  • We use Greedy Algorithms in our day to day life to find minimum number of coins or notes for a given amount. We fist begin with largest denomination and try to use maximum number of the largest and then second largest and so on.
  • Dijkstra’s shortest path algorithm: Finds the shortest path between two nodes in a graph.
  • Kruskal’s and Prim’s minimum spanning tree algorithm: Finds the minimum spanning tree for a weighted graph. Minimum Spanning Trees are used in Computer Networks Designs and have many real world applications
  • Huffman coding: Creates an optimal prefix code for a set of symbols based on their frequencies.
  • Fractional knapsack problem: Determines the most valuable items to carry in a knapsack with a limited weight capacity.
  • Activity selection problem: Chooses the maximum number of non-overlapping activities from a set of activities.
  • Job Sequencing and Job Scheduling Problems.
  • Finding close to the optimal solution for NP-Hard problems like TSP. ide range of network design problems, such as routing, resource allocation, and capacity planning.
  • Machine learning: Greedy algorithms can be used in machine learning applications, such as feature selection, clustering, and classification. In feature selection, greedy algorithms are used to select a subset of features that are most relevant to a given problem. In clustering and classification, greedy algorithms can be used to optimize the selection of clusters or classes
  • Image processing: Greedy algorithms can be used to solve a wide range of image processing problems, such as image compression, denoising, and segmentation. For example, Huffman coding is a greedy algorithm that can be used to compress digital images by efficiently encoding the most frequent pixels.
  • Combinatorics optimization: Greedy algorithms can be used to solve combinatorial optimization problems, such as the traveling salesman problem, graph coloring, and scheduling. Although these problems are typically NP-hard, greedy algorithms can often provide close-to-optimal solutions that are practical and efficient.
  • Game theory: Greedy algorithms can be used in game theory applications, such as finding the optimal strategy for games like chess or poker. In these applications, greedy algorithms can be used to identify the most promising moves or actions at each turn, based on the current state of the game.

Advantages of Greedy Algorithms:

  • Simple and easy to understand: Greedy algorithms are often straightforward to implement and reason about.
  • Efficient for certain problems: They can provide optimal solutions for specific problems, like finding the shortest path in a graph with non-negative edge weights.
  • Fast execution time: Greedy algorithms generally have lower time complexity compared to other algorithms for certain problems.
  • Intuitive and easy to explain : The decision-making process in a greedy algorithm is often easy to understand and justify.
  • Can be used as building blocks for more complex algorithms: Greedy algorithms can be combined with other techniques to design more sophisticated algorithms for challenging problems.

Disadvantages of the Greedy Approach:

  • Not always optimal: Greedy algorithms prioritize local optima over global optima, leading to suboptimal solutions in some cases.
  • Difficult to prove optimality: Proving the optimality of a greedy algorithm can be challenging, requiring careful analysis.
  • Sensitive to input order: The order of input data can affect the solution generated by a greedy algorithm.
  • Limited applicability: Greedy algorithms are not suitable for all problems and may not be applicable to problems with complex constraints.

Greedy Algorithm Most Asked Interview Problems :

Some of the popular problems on the Greedy Approach that are widely asked in interviews are:

Problems

Activity Selection Problem

Kruskal’s Minimum Spanning Tree Algorithm

Huffman Coding

Efficient Huffman Coding for Sorted Input

Prim’s Minimum Spanning Tree Algorithm

Prim’s MST for Adjacency List Representation

Dijkstra’s Shortest Path Algorithm

Job Sequencing Problem

Greedy Algorithm to find Minimum number of Coins

K Centers Problem

Connect n ropes with minimum cost

Graph coloring

Fractional Knapsack Problem

Minimize Cash Flow among a given set of friends who have borrowed money from each other

Find minimum time to finish all jobs with given constraints

Find maximum sum possible equal to sum of three stacks

Minimum Number of Platforms Required for a Railway/Bus Station

Greedy Algorithm Tutorial – FAQs

What is a greedy algorithm?

A greedy algorithm is an algorithm that makes the best local choice at each step in the hope of finding the global optimum solution. It is a heuristic approach, meaning it does not guarantee finding the optimal solution but often provides a good approximation.

When should I use a greedy algorithm?

Greedy algorithms are best suited for problems where optimal substructure exists. This means that the optimal solution to the problem can be constructed from the optimal solutions to its subproblems. Examples of problems where greedy algorithms are effective include Dijkstra’s shortest path algorithm, Kruskal’s minimum spanning tree algorithm, and Huffman coding .

What are the advantages and disadvantages of greedy algorithms?

Advantages of greedy algorithms:

  • Easy to understand and implement.
  • Often computationally efficient.
  • Can provide good approximate solutions even when the optimal solution is difficult to find.

Disadvantages of greedy algorithms:

  • Do not always guarantee finding the optimal solution.
  • May not be applicable to all problems.

What are some examples of greedy algorithms?

Below are some example of greedy algorithms:

  • Dijkstra’s shortest path algorithm
  • Kruskal’s minimum spanning tree algorithm
  • Huffman coding
  • Fractional knapsack problem
  • Activity selection problem

Where can I learn more about greedy algorithms?

There are many resources available online and in textbooks to learn more about greedy algorithms. Some good resource to start learning Greedy algorithms are:

  1. GeeksforGeeks
  2. MIT OpenCourseware:

Related Articles:



Next Article

Similar Reads

three90RightbarBannerImg