Pick the best-looking choice at each step. You learn when that works (Huffman, scheduling) and when it fails.
Open the interactive lessons →Greedy Algorithms past questions
Contents
- What greedy means, and when it works
- Huffman coding: shorter codes for common symbols
- Interval scheduling and meeting rooms
- 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 word | Meaning |
|---|---|
| greedy choice | the option that looks best now, never revised |
| optimal | no other solution is better |
| counter-example | one input where the method fails |
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.
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.
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.
| Problem | Greedy rule | Optimal? | Why / counter-example |
|---|---|---|---|
| activity selection (most activities) | earliest finish time first | yes | exchange argument |
| activity selection | earliest start first | no | one long early activity blocks many short ones |
| activity selection | shortest first | no | a short activity can sit in the middle and block two others |
| min max lateness | earliest deadline first | yes | exchange argument |
| min max lateness | shortest job first | no | a short job with a far deadline delays an urgent one |
| Huffman coding | merge two smallest | yes | exchange argument |
| coin change (any coins) | largest coin first | no | coins 1, 5, 12, 15 paying 24 (below) |
| coin change (1, 5, 10, 25 style) | largest coin first | yes for these denominations | special structure |
| shortest path with negative edges | Dijkstra's greedy choice | no | a 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
| coins | amount | greedy (largest first) | best possible | counter-example? |
|---|---|---|---|---|
| [1, 5, 12, 15] | 24 | 6 | 2 | yes |
| [1, 4, 6] | 8 | 3 | 2 | yes |
| [1, 2, 5] | 18 | 5 | 5 | no |
| [1, 8, 9] | 16 | 8 | 2 | yes |
| [1, 5, 10, 25] | 41 | 4 | 4 | no |
Worked example: Disprove a greedy rule
Problem.
Coins $\{1,3,4\}$, pay 6. Does largest-first work?
Idea.
Compare greedy with another split.
- Greedy: 4, then 1, then 1 = 3 coins.
- Better: 3 + 3 = 2 coins.
- 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.
- 725 odd: subtract 1 → 724 (1 step).
- 724→362→181 (halve twice: 3 steps so far).
- 181→180→90→45→44→22→11→10→5→4→2→1.
- 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 mistake | Correction |
|---|---|
| "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 proven | one example proves nothing for correctness; one counter-example disproves |
| choosing the greedy rule by taste | test it on a tiny input that tries to break it |
Mnemonic "Greedy needs a Guarantee". Before trusting a greedy rule, try to break it with a tiny input.
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 argument | Activity 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 unchanged | still 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.
- x=11: greedy 9+1+1 = 3 coins; 6+5 = 2 coins.
- 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.
- Checked every amount 1..100 by program.
- 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.
- Greedy takes 10, then four 1s: 5 coins.
- 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.
Break it or prove it.
| Step | Method for any exam question |
|---|---|
| 1 | State the rule. |
| 2 | Try small cases to break it. |
| 3 | If 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 word | Meaning |
|---|---|
| prefix code | no code word is the beginning of another |
| frequency | how often a symbol occurs |
| depth of a symbol | the length of its code |
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 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 set | Prefix-free? | Reason |
|---|---|---|
| A:0, B:1, C:01, D:10 | no | 0 is a prefix of 01; 1 is a prefix of 10 |
| A:0, B:10, C:110, D:111 | yes | no code starts another |
| A:1, B:01, C:001, D:000 | yes | all end where they split |
| A:00, B:01, C:10, D:11 | yes | fixed 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.
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.
Cost of a tree = sum of frequency × depth. Take any best tree, and let $x,y$ be the two rarest symbols.
- A deepest leaf $d$ must have a sibling, otherwise it could move up and save bits.
- 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.
- 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)$.
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.
| Property | True? | Reason |
|---|---|---|
| higher-frequency symbols are closer to the root | true | merged last |
| lower-frequency symbols are closer to the root | false | merged first, so they end deeper |
| the tree is a strict binary tree (every internal node has 2 children) | true | every merge makes a node with exactly 2 children |
| the tree is a complete binary tree | false | depths can differ a lot |
| it generates prefix codes | true | symbols are leaves |
| the two lowest-frequency symbols have equal code length (distinct frequencies) | true | they are merged first, so siblings |
| there is always a symbol with code length 1 | false | four 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.
- Merge 5 and 9 → 14.
- Merge 12 and 14 → 26.
- c is at depth 1; a and b at depth 2.
- 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.
- Before: $2000\cdot5=10000$ bits. After: $2000\cdot3.5=7000$ bits.
- Saved 3000 bits.
- $3000/10000=30\%$.
Answer.
30 percent
Common mistake.
Dividing by 3.5 instead of 5: the base is the original size.
| Common mistake | Correction |
|---|---|
| merging the two largest | always the two smallest |
| adding 0 and 1 wrongly so lengths differ from depths | length = depth of the leaf |
| mixing "sum of lengths" with "sum of freq x length" | read what the question asks |
| saying the Huffman tree is complete | it is strict (full), not complete |
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)
Every symbol is a one-node tree; the number under it is its frequency. They wait in a min-heap.
Remove the two smallest trees: a (5) and b (9).
Join them under a new node of weight 14 (left edge 0, right edge 1) and push it back.
Remove the two smallest trees: c (12) and d (13).
Join them under a new node of weight 25 (left edge 0, right edge 1) and push it back.
Remove the two smallest trees: subtree 14 (14) and e (16).
Join them under a new node of weight 30 (left edge 0, right edge 1) and push it back.
Remove the two smallest trees: subtree 25 (25) and subtree 30 (30).
Join them under a new node of weight 55 (left edge 0, right edge 1) and push it back.
Remove the two smallest trees: f (45) and subtree 55 (55).
Join them under a new node of weight 100 (left edge 0, right edge 1) and push it back.
One tree remains. Follow edges from the root to each leaf. Total bits (frequency × code length) = 224, the sum of all merge weights.
| symbol | frequency | code length | bits |
|---|---|---|---|
| a | 5 | 4 | 20 |
| b | 9 | 4 | 36 |
| c | 12 | 3 | 36 |
| d | 13 | 3 | 39 |
| e | 16 | 3 | 48 |
| f | 45 | 1 | 45 |
| total | 100 | 224 |
Fixed-length coding of 6 symbols needs 3 bits each: $100\cdot3=300$ bits. Huffman needs 224 bits, a saving of $76/300\approx25\%$.
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$.
- Merge 0.1+0.2 = 0.3; then 0.3+0.3 = 0.6; then 0.4+0.6 = 1.
- Lengths: 0.4 → 1, 0.3 → 2, 0.2 → 3, 0.1 → 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.
- Merge the two 1s → 2. Now three weights tie at 2: the two leaves and the new node.
- 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$.
- 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.
- Merge $1+1=2$, then $2+2=4$.
- Then $3+4=7$, $5+7=12$, $8+12=20$.
- Add the merged weights: $2+4+7+12+20$.
Answer.
$45$ bits
Common mistake.
Adding only the final weight 20.
Always merge the two smallest.
| Step | Method for any exam question |
|---|---|
| 1 | List the weights. |
| 2 | Merge the two smallest. |
| 3 | Repeat until one tree remains. |
| 4 | Read 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 word | Meaning |
|---|---|
| compatible | two activities that do not overlap |
| earliest finish | the rule of choosing what ends first |
| depth | the largest number of activities running at one time |
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.
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.
| Rule | Works? | Counter-example |
|---|---|---|
| earliest start first | no | (0,10) and (1,2), (3,4), (5,6): picks (0,10) first, only 1 activity instead of 3 |
| shortest duration first | no | (1,6), (5,8), (7,12): the middle one is shortest but blocks two; best is 2 activities, shortest gives 1 |
| earliest finish first | yes | proved 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) | start | finish | finish of last chosen | take? |
|---|---|---|---|---|
| B2 | 0 | 3 | - | yes |
| B3 | 2 | 5 | 3 | no (2 < 3) |
| B5 | 3 | 6 | 3 | yes |
| B4 | 1 | 7 | 6 | no (1 < 6) |
| B7 | 6 | 8 | 6 | yes |
| B6 | 4 | 9 | 8 | no (4 < 8) |
| B1 | 7 | 10 | 8 | no (7 < 8) |
| B8 | 8 | 11 | 8 | yes |
| B10 | 9 | 13 | 11 | no (9 < 11) |
| B9 | 11 | 15 | 11 | yes |
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. 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.
- At time 4.5: (0,5), (2,9), (3,6), (4,8) are all running: 4 meetings.
- 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
| time | event | meetings 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 mistake | Correction |
|---|---|
using > so an activity starting at the end time is rejected | the PYQs say starting at $T$ is allowed: use >= |
| sorting by start for activity selection | sort by finish |
| counting rooms as the number of meetings | count simultaneous meetings only |
| giving the sweep start before end at the same time | ends first, so room reuse at the same time works |
Mnemonic "Finish Fast, Fit Many". One room: earliest finish. Many rooms: busiest instant.
Earliest-finish sweep, bar by bar
Sort the activities by finish time (top bar finishes first). Then sweep down once.
P is (1, 3). Does it start at or after the last chosen finish? Nothing is chosen yet.
Yes, so take P. The last finish moves to 3.
U is (3, 4). Does it start at or after the last chosen finish, 3?
Yes, so take U. The last finish moves to 4.
Q is (2, 5). Does it start at or after the last chosen finish, 4?
No: 2 < 4, so Q overlaps a chosen activity. Skip it.
R is (4, 7). Does it start at or after the last chosen finish, 4?
Yes, so take R. The last finish moves to 7.
S is (6, 9). Does it start at or after the last chosen finish, 7?
No: 6 < 7, so S overlaps a chosen activity. Skip it.
T is (8, 10). Does it start at or after the last chosen finish, 7?
Yes, so take T. The last finish moves to 10.
Chosen P, U, R, T: 4 activities, the most possible.
Minimum rooms: each meeting goes to a free room or opens a new one
M1 (0, 4): every open room is busy at time 0, so open room 1.
M2 (1, 3): every open room is busy at time 1, so open room 2.
M3 (2, 6): every open room is busy at time 2, so open room 3.
M6 (3, 5): room 2 became free at 3 ≤ 3, so reuse it.
M4 (5, 8): room 1 became free at 4 ≤ 5, so reuse it.
M5 (7, 9): room 2 became free at 5 ≤ 7, so reuse it.
3 rooms were opened, which equals the largest number of meetings running at the same moment.
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 wording | Which method | Answer type |
|---|---|---|
| "maximum number of activities / meetings in one room" | earliest-finish scan | a count of chosen activities |
| "minimum number of rooms / halls / machines" | sweep for the peak overlap | a count of rooms |
| "which greedy strategy is optimal" | earliest finish | a rule |
| events already given in time order | running count +1 / −1 | the 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 ≥.
- Sorted: (1,3), (3,5), (5,7).
- 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.
- The shortest is $(4,6)$.
- It overlaps both others, so only 1 is taken.
- $(0,5)$ and $(5,10)$ fit together.
Answer.
Shortest first: 1. Best: 2.
Common mistake.
Assuming short activities always leave more room.
One room: earliest finish. Rooms: peak overlap.
| Step | Method for any exam question |
|---|---|
| 1 | One room: sort by finish time. |
| 2 | Take each meeting that starts after the last one ends. |
| 3 | Many 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 word | Meaning |
|---|---|
| deadline | the time by which a job is due |
| lateness | finish time minus deadline, or 0 if on time |
| exchange argument | swapping two neighbours never makes the answer worse |
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.
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.
| Rule | Correct? | Why or counter-example |
|---|---|---|
| earliest deadline first | yes | exchange argument below |
| shortest processing time first | no | jobs (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$ first | no | X(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 first | no | no 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$ |
|---|---|---|---|---|
| C2 | 2 | 3 | 2 | 0 |
| C3 | 4 | 6 | 6 | 0 |
| C1 | 3 | 9 | 9 | 0 |
| C4 | 1 | 11 | 10 | 0 |
| C5 | 5 | 13 | 15 | 2 |
| C6 | 2 | 16 | 17 | 1 |
Seven jobs: EDF order and lateness
| job (in deadline order) | duration $T$ | deadline $D$ | finish $F$ | lateness $L$ |
|---|---|---|---|---|
| E2 | 2 | 3 | 2 | 0 |
| E4 | 4 | 6 | 6 | 0 |
| E1 | 5 | 8 | 11 | 3 |
| E5 | 1 | 10 | 12 | 2 |
| E7 | 2 | 12 | 14 | 2 |
| E3 | 3 | 15 | 17 | 2 |
| E6 | 6 | 18 | 23 | 5 |
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.
- Order by deadline: (2,3), (3,4), (4,10).
- Finish times 2, 5, 9. Lateness: max(0,2-3)=0; max(0,5-4)=1; max(0,9-10)=0.
- Maximum = 1.
Answer.
1
Common mistake.
Using the order given in the table instead of sorting.
| Common mistake | Correction |
|---|---|
| sorting by shortest duration | sort by deadline |
| forgetting that lateness is never negative | early jobs count as 0 |
| inserting idle gaps | never idle; it only delays everything |
| not accumulating the finish times | finish = running sum of durations |
Mnemonic "Due Date First". The one due soonest goes first.
Earliest deadline first on six jobs
J1 (T=3, D=6) runs from 0 to 3. Lateness $=\max(0,3-6)=0$.
J2 (T=2, D=8) runs from 3 to 5. Lateness $=\max(0,5-8)=0$.
J3 (T=1, D=9) runs from 5 to 6. Lateness $=\max(0,6-9)=0$.
J4 (T=4, D=9) runs from 6 to 10. Lateness $=\max(0,10-9)=1$.
J5 (T=3, D=14) runs from 10 to 13. Lateness $=\max(0,13-14)=0$.
J6 (T=2, D=15) runs from 13 to 15. Lateness $=\max(0,15-15)=0$.
Largest lateness is 1. No other order can make it smaller.
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.
- EDF runs (1,1) first: finish 1, lateness 0; then (2,3): finish 3, lateness 0.
- 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.
- Shortest first: finishes at 1 and 6; the second is 1 late.
- 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.
Earliest deadline first.
| Step | Method for any exam question |
|---|---|
| 1 | Sort by deadline. |
| 2 | Add durations to get finish times. |
| 3 | Subtract each deadline. |
| 4 | Take the largest. |