4 Greedy Algorithms

Design and Analysis of Algorithms · Unit 4 · 6 hrs

Greedy Algorithms

Exam-focused notes for Greedy Algorithms (Design and Analysis of Algorithms, CSC325): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Greedy Algorithms in short

A greedy algorithm builds a solution step by step, at each step making the choice that looks best right now and never revisiting it. This unit sets out when that shortcut is provably correct, then applies it to the minimum spanning tree, shortest path, scheduling, and data compression problems that are its classic successes.

Greedy Algorithms: notes

Optimization Problems and Optimal Solution, Introduction of Greedy Algorithms, Elements of Greedy Strategy

An optimization problem asks for the best solution, by some objective function, among all feasible solutions; it is discrete when the variables are chosen from a finite or countable set (as in every algorithm in this unit) and continuous otherwise. A solution is globally optimal if no other feasible solution has a better objective value, and merely locally optimal if no feasible solution in its immediate neighbourhood is better.

A greedy algorithm is correct only when the problem has two properties. The greedy choice property says that a globally optimal solution can be reached by making the choice that looks best at the current step, without reconsidering it later. Optimal substructure says that an optimal solution to the whole problem contains within it optimal solutions to its sub-problems. Five components describe any greedy algorithm: a candidate set from which a solution is assembled, a selection function that picks the most promising remaining candidate, a feasibility function that checks whether adding a candidate keeps the partial solution valid, an objective function that scores a (partial) solution, and a solution function that recognizes when a complete solution has been reached.

What this unit covers

  • Optimization Problems and Optimal Solution, Introduction of Greedy Algorithms, Elements of Greedy Strategy
  • Greedy Algorithms: Fractional Knapsack, Job sequencing with Deadlines, Kruskal's Algorithm, Prims Algorithm, Dijkstra's Algorithm and their Analysis
  • Huffman Coding: Purpose of Huffman Coding, Prefix Codes, Huffman Coding Algorithm and its Analysis

Huffman Coding

2082 · 10 marks

How do you define optimal solution? Does greedy algorithm always guarantee optimal solution? Given the string "SUPER DUPER CSIT", use a Greedy algorithm to build a Huffman tree.[10]

An optimal solution is the best possible feasible solution to a problem: the one that maximizes or minimizes the objective function (maximum profit, minimum cost, shortest path, etc.) while satisfying all constraints. Among all feasible solutions, the optimal one gives the most efficient/best obj...

Open this answer on its own page →

2080 · 5 marks

Suppose that a message contains alphabet frequencies as given below and find Huffman codes for each alphabet.

SymbolFrequency
a30
b20
c25
d15
e35

[5]

Symbol Frequency ------------------- a 30 b 20 c 25 d 15 e 35 Total frequency $= 30 + 20 + 25 + 15 + 35 = 125$ --- Sort ascending: d(15), b(20), c(25), a(30), e(35) Node db(35) Remaining: c(25), a(30), e(35), db(35) Node ca(55) Remaining: e(35), db(35), ca(55) Node edb(70) Remaining: ca(55), edb(...

Open this answer on its own page →

2079 · 5 marks

Generate the prefix code for the string "CYBER CRIME" using Huffman algorithm and find the total number of bits required. [5]

String: CYBER CRIME (11 characters including one space) Character frequencies: Character Frequency ---------------------- C 2 Y 1 B 1 E 2 R 2 Space 1 I 1 M 1 Total = $2+1+1+2+2+1+1+1 = 11$ characters, 8 distinct symbols. --- Order the nodes by frequency. There are five nodes of frequency 1 and th...

Open this answer on its own page →

Greedy Algorithms

2081 · 10 marks

Does greedy algorithm guarantee optimal solution? Solve the Fractional knapsack problem to find maximum loot from given information.

Item1234567
Value121020152350
Weight (kgs)213212101

[10]

Item 1 2 3 4 5 6 7 --------------------------- Value 12 10 20 15 2 3 50 Weight (kg) 2 1 3 2 12 10 1 Missing data: The knapsack capacity $W$ is not given in the problem. This is essential to solve the fractional knapsack. This solution assumes $W = 15$ kg, which must be flagged as an assumption. -...

Open this answer on its own page →

2080 · 5 marks

When greedy strategy provides optimal solution? Write down job sequencing with deadlines algorithm and analyze its complexity. [5]

A greedy strategy provides an optimal solution when the problem satisfies the following conditions: 1. Greedy Choice Property: A globally optimal solution can be reached by making a locally optimal (greedy) choice at each step. That is, the choice that looks best at the current moment leads to th...

Open this answer on its own page →

2079 · 5 marks

Find the MST from following graph using Kruskal's algorithm. [5]

The question asks to find the MST from a given graph using Kruskal's algorithm. Missing data: No graph image, adjacency matrix, edge list, or vertex/weight information was provided with the question. The actual graph is unreadable/absent. Because no numeric edge weights are given, the specific MS...

Open this answer on its own page →

2078 · 5 marks

Explain the algorithm and its complexity for solving job sequencing with deadline problem using greedy strategy. [5]

Show solved answer

Job Sequencing with Deadlines - Greedy Strategy

Problem Statement

Given n jobs, each with a deadline and a profit (earned only if the job is completed by its deadline), find a feasible sequence of jobs that maximizes total profit. Each job takes unit time to complete and only one machine (processor) is available.


Greedy Strategy

The greedy approach selects jobs in decreasing order of profit (most profitable job first) and schedules each job in the latest available time slot before its deadline.


Algorithm

JobSequencingWithDeadline(D, J, n, k)

1. Sort all jobs in decreasing order of profit P.
2. D(0) = J(0) = 0
3. k = 1
4. J(1) = 1        // Select the first (highest profit) job
5. for i = 2 to n do:
      r = k
      while D(J(r)) > D(i) and D(J(r)) ≠ r do:
          r = r - 1
      if D(J(r)) ≤ D(i) and D(i) > r then:
          for l = k downto r+1 do:
              J(l+1) = J(l)
          J(r+1) = i
          k = k + 1
6. Output J(1), J(2), ..., J(k)  // Feasible job sequence with max profit

Step-by-Step Example

JobDeadlineProfit
J12100
J2119
J3227
J4125
J5315

After sorting by profit (descending): J1(100), J3(27), J4(25), J2(19), J5(15)

  • Select J1 → place at slot 2 → Schedule: [_, J1]
  • Select J3 → deadline 2, slot 1 is free → Schedule: [J3, J1]
  • Select J4 → deadline 1, slot 1 is taken → skip
  • Select J2 → deadline 1, slot 1 is taken → skip
  • Select J5 → deadline 3, slot 3 is free → Schedule: [J3, J1, J5]

Result: J3, J1, J5 with total profit = 27 + 100 + 15 = 142


Complexity Analysis

PhaseOperationComplexity
Sorting jobs by profitComparison sortO(n log n)
Selecting and inserting each jobInner while loop (at most k iterations per job)O(n²) in worst case
  • The outer loop runs n times.
  • The inner while loop and shifting loop together run at most O(n) per iteration.
  • Therefore, the overall time complexity is:

$$T(n) = O(n^2)$$

The dominant term is the job insertion step, making the overall complexity O(n²).


Summary

AspectDetail
StrategyGreedy (highest profit first)
Key IdeaSchedule each job in latest available slot before deadline
Time ComplexityO(n²)
OptimalityGives optimal (maximum profit) feasible schedule
Open this answer on its own page →

2076 · 5 marks

Explain the greedy algorithm for the fractional knapsack problem with its time complexity. [5]

A thief has a knapsack that can carry a maximum weight W. There are n items, where the i-th item has: - Weight: w[i] - Value: v[i] Any fraction of an item can be taken (unlike 0/1 knapsack). The objective is to maximize total profit by selecting items or fractions of items. --- The greedy approac...

Open this answer on its own page →

2076 · 5 marks

Explain Prim’s algorithm for MST problem and analyze its time complexity. [5]

A Minimum Spanning Tree (MST) of a weighted, connected, undirected graph is a spanning tree whose total edge weight is minimum among all possible spanning trees. Prim's Algorithm is a greedy algorithm that builds the MST by starting from an arbitrary vertex and repeatedly adding the minimum weigh...

Open this answer on its own page →

Optimization Problems and Optimal Solution, Introduction of Greedy Algorithms, Elements of Greedy Strategy

2078 · 5 marks

What do you mean by optimization problem? Explain the greedy strategy for algorithm design to solve optimization problems. [5]

Show solved answer

Optimization Problem and Greedy Strategy

Optimization Problem

An optimization problem is the problem of finding the best solution from all feasible solutions. The goal is either to maximize or minimize some objective function subject to given constraints.

Optimization problems can be divided into two categories:

  • Discrete Optimization: Variables are discrete (e.g., integer values). Examples include knapsack problem, shortest path problem, etc.
  • Continuous Optimization: Variables are continuous. These include constrained problems and multimodal problems.

Greedy Strategy for Algorithm Design

The greedy strategy (or greedy method) is an algorithmic approach that builds up a solution piece by piece, always choosing the next piece that offers the most immediate or local benefit (the locally optimal choice) at each step, with the hope of finding a global optimum.

Key Idea

At each step, make the choice that looks best at the moment without reconsidering previous choices.

Characteristics of Greedy Strategy

PropertyDescription
Greedy Choice PropertyA globally optimal solution can be arrived at by making locally optimal (greedy) choices at each step.
Optimal SubstructureAn optimal solution to the problem contains optimal solutions to its subproblems.
No BacktrackingOnce a choice is made, it is never reconsidered.

General Steps of Greedy Algorithm

  1. Initialize an empty solution set.
  2. Select the best available candidate (greedy choice) from the remaining options.
  3. Check feasibility: Determine if the selected candidate can be added to the solution without violating constraints.
  4. Add the candidate to the solution if feasible.
  5. Repeat steps 2-4 until a complete solution is obtained.

Example: Activity Selection Problem

Given a set of activities with start and finish times, select the maximum number of non-overlapping activities.

Greedy Choice: Always select the activity that finishes earliest among the remaining compatible activities.

Activities sorted by finish time:
A1(1,3), A2(2,5), A3(4,6), A4(6,8)

Step 1: Select A1 (earliest finish = 3)
Step 2: A2 overlaps with A1, skip
Step 3: Select A3 (start=4 >= finish of A1=3)
Step 4: Select A4 (start=6 >= finish of A3=6)

Result: {A1, A3, A4} --> Maximum 3 activities

Advantages of Greedy Strategy

  • Simple and easy to implement.
  • Generally faster than dynamic programming (often O(n log n) or O(n)).
  • Works well when greedy choice property and optimal substructure hold.

Limitations

  • Does not always produce a globally optimal solution.
  • Cannot be applied to all optimization problems (e.g., 0/1 Knapsack does not yield optimal result with greedy).

Common Problems Solved Using Greedy Strategy

  • Fractional Knapsack Problem
  • Huffman Coding
  • Prim's and Kruskal's Minimum Spanning Tree
  • Dijkstra's Shortest Path Algorithm
  • Activity Selection Problem

In summary, the greedy strategy solves optimization problems by making the locally best choice at each step, which leads to an efficient and often optimal solution when the problem satisfies the greedy choice property and optimal substructure.

Open this answer on its own page →