Greedy Algorithms

Pick the best-looking choice at each step. You learn when that works (Huffman, scheduling) and when it fails.

4 lessons · 26 past questions · 84 marks in the papers collected here

Open the interactive lessons →Greedy Algorithms past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. What greedy means, and when it works
  2. Huffman coding: shorter codes for common symbols
  3. Interval scheduling and meeting rooms
  4. Minimizing the maximum lateness

1. What greedy means, and when it works

Greedy = pick what looks best right now. It is fast, but only some problems let it be correct.

The greedy method: make the best-looking choice now and never undo it.

The question this lesson answers. How do you tell whether a greedy rule really works?

New wordMeaning
greedy choicethe option that looks best now, never revised
optimalno other solution is better
counter-exampleone input where the method fails
Picture it

Filling a plate at a buffet by always taking the tastiest item that still fits, and never putting anything back. Sometimes that is the best plate, sometimes not.

A greedy algorithm builds a solution step by step. At each step it picks the option that looks best right now (the largest coin, the earliest finishing meeting, the two smallest weights) and never reconsiders. It is usually simple and fast, often $O(n\log n)$ because of a sort or a heap.

Definition

Greedy choice + no regret. A greedy algorithm repeatedly makes a locally best choice and commits to it. It is correct only when a proof shows that the locally best choice can always be extended to a globally best answer.

Why it works. One counter-example is enough to reject a rule, while accepting it needs an argument that swapping in the greedy choice never makes things worse.

Two facts the exam tests

Greedy does not always give the optimal answer. PYQ statement "the greedy technique always gives an optimized solution" is false. Also, Bellman-Ford and Floyd-Warshall are dynamic programming, not greedy; Dijkstra and Prim are greedy.

Analogy: hiking up a mountain in fog by always stepping uphill. You may reach a small hill and stop. Limit: if the mountain has only one peak (a "greedy-friendly" shape), always going uphill works.

The standard proof idea (exchange argument). Take any optimal solution that does something different from greedy at the first step. Show you can swap its first choice for greedy's choice without making the answer worse. Repeat, and the optimal solution turns into the greedy one. We use this idea for scheduling and for Huffman.

How to disprove a greedy rule. Find one small input where greedy gives a worse answer than another method. One such input is a counter-example and kills the rule.

ProblemGreedy ruleOptimal?Why / counter-example
activity selection (most activities)earliest finish time firstyesexchange argument
activity selectionearliest start firstnoone long early activity blocks many short ones
activity selectionshortest firstnoa short activity can sit in the middle and block two others
min max latenessearliest deadline firstyesexchange argument
min max latenessshortest job firstnoa short job with a far deadline delays an urgent one
Huffman codingmerge two smallestyesexchange argument
coin change (any coins)largest coin firstnocoins 1, 5, 12, 15 paying 24 (below)
coin change (1, 5, 10, 25 style)largest coin firstyes for these denominationsspecial structure
shortest path with negative edgesDijkstra's greedy choicenoa later negative edge can shorten a finished vertex

Coin counter-example. Coins $\{1,5,12,15\}$, pay 24. Greedy takes 15, then 5, then four 1s: 6 coins. The best is 12 + 12 = 2 coins. So largest-first is not optimal here.

Testing greedy on five coin sets

coinsamountgreedy (largest first)best possiblecounter-example?
[1, 5, 12, 15]2462yes
[1, 4, 6]832yes
[1, 2, 5]1855no
[1, 8, 9]1682yes
[1, 5, 10, 25]4144no

Worked example: Disprove a greedy rule

Problem.

Coins $\{1,3,4\}$, pay 6. Does largest-first work?

Idea.

Compare greedy with another split.

  1. Greedy: 4, then 1, then 1 = 3 coins.
  2. Better: 3 + 3 = 2 coins.
  3. So greedy is not optimal.

Answer.

no: 3 coins vs 2 coins

Common mistake.

Testing only the amounts where greedy happens to win.

Worked example: Doubling puzzle (PYQ style)

Problem.

Start at $x=1$. A step is $+1$ or $\times2$. Fewest steps to reach 725.

Idea.

Work backwards: if the target is even halve it, if odd subtract 1.

  1. 725 odd: subtract 1 → 724 (1 step).
  2. 724→362→181 (halve twice: 3 steps so far).
  3. 181→180→90→45→44→22→11→10→5→4→2→1.
  4. Count all moves; a BFS in code confirms the total is 14.

Answer.

14

Common mistake.

Going forward greedily (always doubling) overshoots the target.

Common mistakeCorrection
"greedy is always optimal"false: it needs a proof
"Bellman-Ford is greedy"it is dynamic programming (it relaxes all edges repeatedly)
testing one example and calling it provenone example proves nothing for correctness; one counter-example disproves
choosing the greedy rule by tastetest it on a tiny input that tries to break it
Memory trick

Mnemonic "Greedy needs a Guarantee". Before trusting a greedy rule, try to break it with a tiny input.

Why a greedy rule can be trusted

Exchange argument (how greedy is proved). Take any optimal answer $O$. If it differs from the greedy answer $G$ at the first step, swap $O$'s choice for the greedy choice and show the answer is no worse. Repeat; you turn $O$ into $G$ without losing anything, so $G$ is optimal too.

Step of the argumentActivity selection example
1. take an optimal schedule $O$$O$ starts with some activity $x$
2. greedy picks $g$ with the earliest finish$f(g)\le f(x)$
3. swap $x$ for $g$ in $O$$g$ ends no later, so it still fits before the rest
4. the size is unchangedstill optimal, now agrees with greedy on step 1
5. repeat for the remaining activities$O$ becomes the greedy schedule

Worked example: Build a counter-example yourself

Problem.

Rule: "pay with the largest coin first". Coins {1, 5, 6, 9}. Find an amount where greedy is not optimal.

Idea.

Try amounts just above a large coin.

  1. x=11: greedy 9+1+1 = 3 coins; 6+5 = 2 coins.
  2. So x = 11 is a counter-example.

Answer.

x = 11 (greedy 3, optimal 2).

Common mistake.

Testing only amounts that are themselves coins.

Worked example: Greedy that is optimal for coins

Problem.

Indian coins {1, 2, 5, 10}. Is largest-first optimal for every amount up to 100?

Idea.

Compare greedy with dynamic programming for every amount.

  1. Checked every amount 1..100 by program.
  2. Greedy count equals the DP minimum each time.

Answer.

Yes. Such coin systems are called canonical.

Common mistake.

Assuming greedy fails for every coin set.

Worked example: Largest-first can waste coins

Problem.

With coins $\{1,7,10\}$, pay 14 by taking the largest coin first. Is that the fewest?

Idea.

Look for a combination the greedy rule never tries.

  1. Greedy takes 10, then four 1s: 5 coins.
  2. Two coins of 7 also make 14.

Answer.

Greedy uses 5 coins; the best uses 2.

Common mistake.

Trusting the rule because it works for other coin sets.

Memory line

Break it or prove it.

StepMethod for any exam question
1State the rule.
2Try small cases to break it.
3If it survives, look for the exchange argument.

2. Huffman coding: shorter codes for common symbols

Give frequent letters short codes and rare letters long codes, using a tree built by repeatedly merging the two smallest weights.

How to compress text with variable-length prefix codes and how to build the code with a min-heap.

The question this lesson answers. How do common letters get shorter codes?

New wordMeaning
prefix codeno code word is the beginning of another
frequencyhow often a symbol occurs
depth of a symbolthe length of its code
Picture it

Text slang: the words used most get the shortest forms.

A computer normally stores each character with the same number of bits (fixed-length code), say 3 bits for up to 8 symbols. But some letters appear far more often than others. If the frequent letters had shorter codes, the message would need fewer bits in total. This is variable-length coding.

Prefix code

Prefix property. In a prefix code no code word is the beginning of another code word. Then a stream of bits can be decoded without separators: as soon as the bits read so far match a code, that symbol is done. Huffman coding always gives a prefix code.

Code setPrefix-free?Reason
A:0, B:1, C:01, D:10no0 is a prefix of 01; 1 is a prefix of 10
A:0, B:10, C:110, D:111yesno code starts another
A:1, B:01, C:001, D:000yesall end where they split
A:00, B:01, C:10, D:11yesfixed length 2: never a prefix of another

Why does a tree give a prefix code? Put the symbols at the leaves of a binary tree. A code is the path from the root: left = 0, right = 1. Two leaves can never lie on the same root-to-leaf path, so no code is a prefix of another.

Algorithm

Huffman algorithm. (1) Make a one-node tree for every symbol with its frequency as weight. (2) Take the two trees of smallest weight, join them under a new node whose weight is the sum. (3) Put the new tree back. (4) Repeat until one tree remains. Read codes: left 0, right 1. A symbol's code length = its depth.

Why merging the two smallest is safe

Cost of a tree = sum of frequency × depth. Take any best tree, and let $x,y$ be the two rarest symbols.

  1. A deepest leaf $d$ must have a sibling, otherwise it could move up and save bits.
  2. Swap $x$ with $d$. The cost changes by $(f_x-f_d)(\text{depth}_d-\text{depth}_x)$. The first factor is $\le 0$ and the second is $\ge 0$, so the cost does not go up.
  3. Swap $y$ with the sibling in the same way.

So some best tree has $x$ and $y$ as deepest siblings: merging them first loses nothing.

Then repeat. Treat the pair as one symbol of frequency $f_x+f_y$. Every tree containing that pair costs the smaller tree's cost plus $f_x+f_y$, so the best choice for the smaller problem is also best for the original.

Huffman with a min-heap

import heapq

def huffman_lengths(freq):               # freq: {symbol: frequency}
    heap = [(f, i, s) for i, (s, f) in enumerate(freq.items())]
    heapq.heapify(heap)                  # min-heap of (weight, tiebreak, tree)
    count = len(heap)
    while len(heap) > 1:
        f1, _, t1 = heapq.heappop(heap)  # smallest
        f2, _, t2 = heapq.heappop(heap)  # second smallest
        heapq.heappush(heap, (f1 + f2, count, (t1, t2)))
        count += 1
    return heap[0][2]                    # the finished tree

Complexity. There are $n-1$ merges, each doing two pops and one push at $O(\log n)$: total $O(n\log n)$.

Which sum?

Two different questions. "Total bits for the whole message" = $\sum f_i\cdot\ell_i$ (frequency times code length). "Total bits to write each symbol once" = $\sum \ell_i$ (just the lengths).

Ties. When two weights tie, different choices can give different code lengths for individual symbols, but the total of frequency × length is the same for every valid Huffman tree. The tie example below shows it.

PropertyTrue?Reason
higher-frequency symbols are closer to the roottruemerged last
lower-frequency symbols are closer to the rootfalsemerged first, so they end deeper
the tree is a strict binary tree (every internal node has 2 children)trueevery merge makes a node with exactly 2 children
the tree is a complete binary treefalsedepths can differ a lot
it generates prefix codestruesymbols are leaves
the two lowest-frequency symbols have equal code length (distinct frequencies)truethey are merged first, so siblings
there is always a symbol with code length 1falsefour equal frequencies give all codes of length 2

Worked example: Smallest example

Problem.

Frequencies a:5, b:9, c:12. Huffman codes lengths and total bits.

Idea.

Merge the two smallest.

  1. Merge 5 and 9 → 14.
  2. Merge 12 and 14 → 26.
  3. c is at depth 1; a and b at depth 2.
  4. Total $=12\cdot1+5\cdot2+9\cdot2=40$ bits.

Answer.

c:1, a:2, b:2, total 40

Common mistake.

Giving c length 2 because "it is not the smallest".

Worked example: Percentage saved (PYQ style)

Problem.

2000 characters, fixed 5 bits each. Huffman average 3.5 bits. Percentage saved?

Idea.

Compare totals.

  1. Before: $2000\cdot5=10000$ bits. After: $2000\cdot3.5=7000$ bits.
  2. Saved 3000 bits.
  3. $3000/10000=30\%$.

Answer.

30 percent

Common mistake.

Dividing by 3.5 instead of 5: the base is the original size.

Common mistakeCorrection
merging the two largestalways the two smallest
adding 0 and 1 wrongly so lengths differ from depthslength = depth of the leaf
mixing "sum of lengths" with "sum of freq x length"read what the question asks
saying the Huffman tree is completeit is strict (full), not complete
Memory trick

Mnemonic "Small-Small-Sum". Take the two Smallest, make a Sum, push it back. Frequent = near the root = short code.

Classic 6-symbol example (a:5, b:9, c:12, d:13, e:16, f:45)

  1. Every symbol is a one-node tree; the number under it is its frequency. They wait in a min-heap.

  2. Remove the two smallest trees: a (5) and b (9).

  3. Join them under a new node of weight 14 (left edge 0, right edge 1) and push it back.

  4. Remove the two smallest trees: c (12) and d (13).

  5. Join them under a new node of weight 25 (left edge 0, right edge 1) and push it back.

  6. Remove the two smallest trees: subtree 14 (14) and e (16).

  7. Join them under a new node of weight 30 (left edge 0, right edge 1) and push it back.

  8. Remove the two smallest trees: subtree 25 (25) and subtree 30 (30).

  9. Join them under a new node of weight 55 (left edge 0, right edge 1) and push it back.

  10. Remove the two smallest trees: f (45) and subtree 55 (55).

  11. Join them under a new node of weight 100 (left edge 0, right edge 1) and push it back.

  12. One tree remains. Follow edges from the root to each leaf. Total bits (frequency × code length) = 224, the sum of all merge weights.

symbolfrequencycode lengthbits
a5420
b9436
c12336
d13339
e16348
f45145
total100224

Fixed-length coding of 6 symbols needs 3 bits each: $100\cdot3=300$ bits. Huffman needs 224 bits, a saving of $76/300\approx25\%$.

Check your answer in 10 seconds

Shortcut for total bits: add up every merge weight. Here $14+25+30+55+100=224$. Each symbol's frequency is added once per level it sits below, which is exactly frequency × depth.

Worked example: Average code length

Problem.

Probabilities 0.4, 0.3, 0.2, 0.1. Average bits per symbol with Huffman?

Idea.

Build the tree, then $\sum p_i\ell_i$.

  1. Merge 0.1+0.2 = 0.3; then 0.3+0.3 = 0.6; then 0.4+0.6 = 1.
  2. Lengths: 0.4 → 1, 0.3 → 2, 0.2 → 3, 0.1 → 3.
  3. Average $=0.4+0.6+0.6+0.3=1.9$.

Answer.

1.9 bits per symbol (versus 2 for fixed length).

Common mistake.

Using the sum of lengths (9) instead of the weighted average.

Worked example: A tie that changes one length

Problem.

Frequencies 1, 1, 2, 2. Can the code lengths be (2, 2, 2, 2) and also (3, 3, 2, 1)?

Idea.

Ties allow different trees with the same total.

  1. Merge the two 1s → 2. Now three weights tie at 2: the two leaves and the new node.
  2. Choice 1: merge the two leaves (2+2 = 4), then 2+4. Every symbol ends at depth 2: lengths 2, 2, 2, 2. Total $2(1+1+2+2)=12$.
  3. Choice 2: merge a leaf with the new node (2+2 = 4), then the other leaf with 4. Lengths: 1s at depth 3, one 2 at depth 2, the other 2 at depth 1. Total $1\cdot3+1\cdot3+2\cdot2+2\cdot1=12$.

Answer.

Both shapes are valid Huffman trees; the total (12 bits) is the same.

Common mistake.

Thinking only one set of lengths is correct.

Worked example: A one-sided tree

Problem.

Build the Huffman tree for frequencies $1,1,2,3,5,8$. What is the total number of encoded bits?

Idea.

The total equals the sum of all merged weights.

  1. Merge $1+1=2$, then $2+2=4$.
  2. Then $3+4=7$, $5+7=12$, $8+12=20$.
  3. Add the merged weights: $2+4+7+12+20$.

Answer.

$45$ bits

Common mistake.

Adding only the final weight 20.

Memory line

Always merge the two smallest.

StepMethod for any exam question
1List the weights.
2Merge the two smallest.
3Repeat until one tree remains.
4Read codes from root to leaf.

3. Interval scheduling and meeting rooms

One room: sort by finish time and take whatever fits. Many rooms: count the maximum number of meetings happening at once.

Choosing the most non-overlapping activities with one room, and the fewest rooms for all meetings.

The question this lesson answers. Which meetings should be accepted, or how many rooms are needed?

New wordMeaning
compatibletwo activities that do not overlap
earliest finishthe rule of choosing what ends first
depththe largest number of activities running at one time
Picture it

Booking one hall: accept the event that frees the hall earliest, so the most time is left for others.

Problem 1: activity selection. We have one room and a list of activities (start, finish). Two activities are compatible if one finishes at or before the other starts (the PYQs say "finish at $T$, next may start at $T$"). Choose as many compatible activities as possible.

Greedy rule

Rule: earliest finish time first. Sort by finish time. Take the first activity. Then walk down the list and take each activity whose start is $\ge$ the finish time of the last one taken.

Why it works. Finishing earliest leaves the most time for the rest; rooms are forced by the greatest number of meetings running together.

Why earliest finish? The activity that finishes first leaves the most room for the remaining ones. Exchange argument: take an optimal schedule; its first activity finishes no earlier than ours. Replace it with ours: still compatible with the rest, and the count is unchanged. So some optimal schedule contains our choice.

RuleWorks?Counter-example
earliest start firstno(0,10) and (1,2), (3,4), (5,6): picks (0,10) first, only 1 activity instead of 3
shortest duration firstno(1,6), (5,8), (7,12): the middle one is shortest but blocks two; best is 2 activities, shortest gives 1
earliest finish firstyesproved by the exchange argument

activity selection

def max_activities(acts):
    acts.sort(key=lambda a: a[1])     # by finish time
    chosen, last_end = [], float("-inf")
    for start, end in acts:
        if start >= last_end:          # compatible: starts at or after the last finish
            chosen.append((start, end))
            last_end = end
    return chosen

Walk through the list

activity (sorted by finish)startfinishfinish of last chosentake?
B203-yes
B3253no (2 < 3)
B5363yes
B4176no (1 < 6)
B7686yes
B6498no (4 < 8)
B17108no (7 < 8)
B88118yes
B1091311no (9 < 11)
B9111511yes

Complexity. Sorting dominates: $O(n\log n)$. The scan is $O(n)$.

Problem 2: minimum number of rooms. Every meeting needs a room, and meetings that overlap need different rooms. The answer is the maximum number of meetings in progress at the same time.

Sweep method

Sweep method. List every start as $+1$ and every end as $-1$. Sort by time; at the same time put ends before starts (because a meeting ending at $t$ frees its room for one starting at $t$). Walk through, keep a running total. The largest total is the number of rooms.

meeting rooms with a min-heap

import heapq

def min_rooms(meetings):
    meetings.sort()                 # by start time
    ends = []                       # min-heap of end times of rooms in use
    for start, end in meetings:
        if ends and ends[0] <= start:
            heapq.heapreplace(ends, end)   # reuse the room that frees first
        else:
            heapq.heappush(ends, end)      # need a new room
    return len(ends)

Worked example: Rooms by sweeping

Problem.

Meetings (0,5), (2,9), (3,6), (4,8), (7,12), (10,14), (11,15), (13,17).

Idea.

Count overlaps at the busiest moment.

  1. At time 4.5: (0,5), (2,9), (3,6), (4,8) are all running: 4 meetings.
  2. No moment has 5 running. By the sweep program: maximum = 4.

Answer.

4

Common mistake.

Counting rooms as the number of meetings that overlap with any one meeting. It must overlap at the same instant.

Sweep for this list: maximum 4 at time 4

timeeventmeetings running
0+(0,5)1
2+(2,9)2
3+(3,6)3
4+(4,8)4
5-(0,5)3
6-(3,6)2
7+(7,12)3
8-(4,8)2
9-(2,9)1
10+(10,14)2
11+(11,15)3
12-(7,12)2
13+(13,17)3
Common mistakeCorrection
using > so an activity starting at the end time is rejectedthe PYQs say starting at $T$ is allowed: use >=
sorting by start for activity selectionsort by finish
counting rooms as the number of meetingscount simultaneous meetings only
giving the sweep start before end at the same timeends first, so room reuse at the same time works
Memory trick

Mnemonic "Finish Fast, Fit Many". One room: earliest finish. Many rooms: busiest instant.

Earliest-finish sweep, bar by bar

  1. Sort the activities by finish time (top bar finishes first). Then sweep down once.

  2. P is (1, 3). Does it start at or after the last chosen finish? Nothing is chosen yet.

  3. Yes, so take P. The last finish moves to 3.

  4. U is (3, 4). Does it start at or after the last chosen finish, 3?

  5. Yes, so take U. The last finish moves to 4.

  6. Q is (2, 5). Does it start at or after the last chosen finish, 4?

  7. No: 2 < 4, so Q overlaps a chosen activity. Skip it.

  8. R is (4, 7). Does it start at or after the last chosen finish, 4?

  9. Yes, so take R. The last finish moves to 7.

  10. S is (6, 9). Does it start at or after the last chosen finish, 7?

  11. No: 6 < 7, so S overlaps a chosen activity. Skip it.

  12. T is (8, 10). Does it start at or after the last chosen finish, 7?

  13. Yes, so take T. The last finish moves to 10.

  14. Chosen P, U, R, T: 4 activities, the most possible.

Minimum rooms: each meeting goes to a free room or opens a new one

  1. M1 (0, 4): every open room is busy at time 0, so open room 1.

  2. M2 (1, 3): every open room is busy at time 1, so open room 2.

  3. M3 (2, 6): every open room is busy at time 2, so open room 3.

  4. M6 (3, 5): room 2 became free at 3 ≤ 3, so reuse it.

  5. M4 (5, 8): room 1 became free at 4 ≤ 5, so reuse it.

  6. M5 (7, 9): room 2 became free at 5 ≤ 7, so reuse it.

  7. 3 rooms were opened, which equals the largest number of meetings running at the same moment.

The two-sided argument

Why rooms = peak overlap. At the busiest moment $k$ meetings run together, so you need at least $k$ rooms. The room-filling procedure above never opens room $k+1$ unless $k+1$ meetings overlap. Lower bound = what the algorithm uses, so it is optimal.

Question wordingWhich methodAnswer type
"maximum number of activities / meetings in one room"earliest-finish scana count of chosen activities
"minimum number of rooms / halls / machines"sweep for the peak overlapa count of rooms
"which greedy strategy is optimal"earliest finisha rule
events already given in time orderrunning count +1 / −1the peak

Worked example: Ends exactly when the next starts

Problem.

Activities (1,3), (3,5), (5,7). Maximum activities if a new one may start at the finish time?

Idea.

Compatibility uses ≥.

  1. Sorted: (1,3), (3,5), (5,7).
  2. 3 ≥ 3, take; 5 ≥ 5, take.

Answer.

3

Common mistake.

Using > and getting 1.

Worked example: Shortest first fails

Problem.

Activities $(0,5)$, $(4,6)$, $(5,10)$. What does "shortest first" achieve, and what is possible?

Idea.

A short activity can block two others.

  1. The shortest is $(4,6)$.
  2. It overlaps both others, so only 1 is taken.
  3. $(0,5)$ and $(5,10)$ fit together.

Answer.

Shortest first: 1. Best: 2.

Common mistake.

Assuming short activities always leave more room.

Memory line

One room: earliest finish. Rooms: peak overlap.

StepMethod for any exam question
1One room: sort by finish time.
2Take each meeting that starts after the last one ends.
3Many rooms: find the largest overlap.

4. Minimizing the maximum lateness

Do the job with the earliest deadline first.

Ordering jobs on one machine so that the worst delay is as small as possible.

The question this lesson answers. In what order should jobs with deadlines be done?

New wordMeaning
deadlinethe time by which a job is due
latenessfinish time minus deadline, or 0 if on time
exchange argumentswapping two neighbours never makes the answer worse
Picture it

Homework with due dates: finishing the one due soonest first keeps the worst delay small.

There are $n$ jobs, each with a processing time $T_i$ and a deadline $D_i$. One job runs at a time, with no gaps, starting at time 0. If job $i$ finishes at $F_i$, its lateness is $L_i=\max(0,F_i-D_i)$. We want an order that makes the largest lateness $M_L=\max_i L_i$ as small as possible.

Greedy rule

Rule: Earliest Deadline First (EDF). Sort jobs by deadline, smallest first. Run them in that order with no idle time.

Why it works. Swapping two neighbours that are out of deadline order never increases the worst lateness.

RuleCorrect?Why or counter-example
earliest deadline firstyesexchange argument below
shortest processing time firstnojobs (T=1,D=100) and (T=2,D=2): shortest-first runs the long-deadline job first, so the urgent one finishes at 3 > 2
smallest slack $D_i-T_i$ firstnoX(T=2,D=10) has slack 8 and Y(T=9,D=11) has slack 2. Slack-first runs Y then X: X ends at 11, lateness 1. EDF runs X then Y: both on time, lateness 0
longest firstnono logic

Check the slack counter-example by program. Jobs X(2,10), Y(9,11): the order Y, X gives maximum lateness 1, the order X, Y (EDF) gives 0.

Exchange argument. Suppose a schedule has two neighbouring jobs $i,j$ with $D_i>D_j$ but $i$ runs first (an inversion). Swap them. Job $i$ finishes later, but its deadline is the later one; job $j$ now finishes earlier. The worst lateness of the pair does not get worse, so we can remove inversions one at a time until the schedule is in deadline order, without increasing $M_L$.

Six jobs: EDF order and lateness

job (in deadline order)duration $T$deadline $D$finish $F$lateness $L$
C22320
C34660
C13990
C4111100
C5513152
C6216171

Seven jobs: EDF order and lateness

job (in deadline order)duration $T$deadline $D$finish $F$lateness $L$
E22320
E44660
E158113
E5110122
E7212142
E3315172
E6618235

EDF

def min_max_lateness(jobs):            # jobs: list of (T, D)
    jobs.sort(key=lambda j: j[1])        # earliest deadline first
    t, worst = 0, 0
    for T, D in jobs:
        t += T                           # finish time of this job
        worst = max(worst, t - D)        # lateness (0 if early)
    return worst

Worked example: Compute minimum lateness

Problem.

Jobs $(T,D)$: (3,4), (2,3), (4,10). Minimum possible $M_L$?

Idea.

Sort by deadline, then accumulate.

  1. Order by deadline: (2,3), (3,4), (4,10).
  2. Finish times 2, 5, 9. Lateness: max(0,2-3)=0; max(0,5-4)=1; max(0,9-10)=0.
  3. Maximum = 1.

Answer.

1

Common mistake.

Using the order given in the table instead of sorting.

Common mistakeCorrection
sorting by shortest durationsort by deadline
forgetting that lateness is never negativeearly jobs count as 0
inserting idle gapsnever idle; it only delays everything
not accumulating the finish timesfinish = running sum of durations
Memory trick

Mnemonic "Due Date First". The one due soonest goes first.

Earliest deadline first on six jobs

  1. J1 (T=3, D=6) runs from 0 to 3. Lateness $=\max(0,3-6)=0$.

  2. J2 (T=2, D=8) runs from 3 to 5. Lateness $=\max(0,5-8)=0$.

  3. J3 (T=1, D=9) runs from 5 to 6. Lateness $=\max(0,6-9)=0$.

  4. J4 (T=4, D=9) runs from 6 to 10. Lateness $=\max(0,10-9)=1$.

  5. J5 (T=3, D=14) runs from 10 to 13. Lateness $=\max(0,13-14)=0$.

  6. J6 (T=2, D=15) runs from 13 to 15. Lateness $=\max(0,15-15)=0$.

  7. Largest lateness is 1. No other order can make it smaller.

Proof idea

Why EDF is optimal (exchange). If a schedule runs job $j$ right before job $i$ while $d_i<d_j$ (an inversion), swap them. Job $i$ finishes earlier, so its lateness does not grow; job $j$ now finishes when $i$ used to, and since $d_j>d_i$ its lateness is at most $i$'s old lateness. So the maximum never increases. Remove every inversion and you get EDF.

Worked example: Idle time never helps

Problem.

Jobs (T=2, D=3), (T=1, D=1). Is waiting before starting ever useful?

Idea.

Delaying a job only makes it finish later.

  1. EDF runs (1,1) first: finish 1, lateness 0; then (2,3): finish 3, lateness 0.
  2. Any idle gap only pushes finish times later.

Answer.

No: an optimal schedule has no idle time.

Common mistake.

Inserting gaps to "wait for" deadlines.

Worked example: Shortest job first fails

Problem.

Jobs (time, deadline): $(1,10)$ and $(5,5)$. Compare the worst lateness of shortest-first with earliest-deadline-first.

Idea.

Add the times and subtract each deadline.

  1. Shortest first: finishes at 1 and 6; the second is 1 late.
  2. Deadline first: finishes at 5 and 6; neither is late.

Answer.

1 against 0.

Common mistake.

Choosing the quick job first because it finishes early.

Memory line

Earliest deadline first.

StepMethod for any exam question
1Sort by deadline.
2Add durations to get finish times.
3Subtract each deadline.
4Take the largest.

Practise this topic →

Other PDSA topics