Greedy Algorithms (DSA Core #8)
A greedy algorithm takes the locally best option and never reconsiders. Sometimes that is provably optimal, and sometimes it is wrong by one counterexample. The job in an interview is to produce the algorithm and the reason it cannot be improved.
The greedy choice property
Two conditions make greedy valid:
- Greedy choice property: a locally optimal choice is part of some globally optimal solution.
- Optimal substructure: after making that choice, the rest of the problem is the same problem on a smaller input.
Interval scheduling has both. Choosing the meeting that ends earliest leaves the most room for everything else; after choosing it, the remaining problem is “schedule meetings starting after this one”, which has the same shape.
Knapsack with fractions has both (take the best value-per-weight first, fill the rest). Knapsack with indivisible items has neither: taking the best ratio can block a better combination (a counterexample is below).
The practical test: if you can describe the state after the greedy choice using only the input that remains, greedy might work. If the choice depends on which items you already took in a way that is not summarized by simple remaining capacity, you need DP.
ASolution
Greedy choice: some optimal solution contains the local best choice. Optimal substructure: after fixing that choice, the rest is an independent subproblem.
Proving greedy correctness
Two proof patterns cover almost every greedy problem.
Exchange argument. Take an optimal solution O that differs from greedy G
at the first step. Swap the greedy choice into O, show the result is still
feasible and no worse, and repeat. Eventually O becomes G, so G is optimal.
Stays-ahead argument. Show that after k steps, greedy’s partial solution is
at least as good as any other algorithm’s after k steps (for example, earliest
finish time, smallest total cost). Induction gives optimality at the end.
Both require the same thing: a measure that does not get worse when you swap. For interval scheduling it is “finish time of the last chosen interval”. For Huffman it is “total weighted path length”. Without a measure, a proof is just a story.
ASolution
Greedy failures are usually constructed, not natural. The coin system {1, 3, 4}
looks fine on small amounts and fails at 6. A proof must cover every input.
Sorting-based greedy
The most common shape: sort by a key, then sweep once. The key is the whole algorithm, and choosing it badly is the usual failure.
| Problem | Sort by | Reason |
|---|---|---|
| Activity selection | end time | finish early leaves the most room |
| Minimum arrows to burst balloons | end coordinate | one arrow covers the earliest-ending group |
| Meeting rooms needed | start time | sweep events in time order |
| Task scheduling with deadlines | deadline | urgent work first |
| Two-city scheduling | cost difference | pairwise exchange |
| Huffman coding | frequency (heap) | merge the two smallest |
Activity selection, in full:
int maxActivities(vector<pair<int,int>> iv) { // {start, end}
sort(iv.begin(), iv.end(), [](auto& a, auto& b) {
return a.second < b.second; // earliest finish first
});
int count = 0, lastEnd = INT_MIN;
for (auto& [s, e] : iv) {
if (s >= lastEnd) { ++count; lastEnd = e; }
}
return count;
}
Sorting by start time, or by duration, fails. Start time can pick a long meeting that blocks three short ones; duration can pick a late short meeting that blocks earlier ones.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=2pt, minimum height=0.42cm, font=\scriptsize}]
\draw[->, thick] (0,0) -- (8.2,0);
\foreach \x in {0,1,...,8} \draw[gray!40] (\x,0.08) -- (\x,-0.08) node[below, font=\tiny] {\x};
\node[b, fill=green!25, minimum width=2.0cm] at (1.1,0.55) {A: 0--2};
\node[b, fill=red!15, minimum width=3.0cm] at (2.2,1.1) {B: 0.7--3.7};
\node[b, fill=green!25, minimum width=1.0cm] at (3.5,0.55) {C: 3--4};
\node[b, fill=green!25, minimum width=3.0cm] at (6.2,0.55) {D: 4.7--7.7};
\node[font=\scriptsize, anchor=north] at (4.0,-0.55) {A, C, D: three meetings; B alone blocks two};
\end{tikzpicture}
Sorting does the hard work, and the sweep is \(O(n \log n)\) with \(O(1)\) extra space. If the input is already sorted, the sweep is \(O(n)\).
time?
ASolution
Finishing earlier leaves a larger remaining time interval, so it cannot reduce future options. Starting earlier says nothing about when the room frees up.
Interval scheduling and activity selection
The interval family has four distinct problems that look alike:
| Problem | Greedy | Complexity |
|---|---|---|
| Max non-overlapping intervals | sort by end, take if start >= lastEnd |
\(O(n \log n)\) |
| Min intervals to remove to make non-overlapping | n - maxNonOverlapping |
\(O(n \log n)\) |
| Min points/arrows to cover all intervals | sort by end, place at end | \(O(n \log n)\) |
| Merge overlapping intervals | sort by start, merge while overlapping | \(O(n \log n)\) |
The third one is the “minimum arrows to burst balloons” pattern: put an arrow at the end of the first interval, skip everything it covers, repeat.
int minArrows(vector<pair<int,int>>& iv) {
sort(iv.begin(), iv.end()); // by start
int arrows = 0;
long long reach = LLONG_MIN;
for (auto& [s, e] : iv) {
if (s > reach) { ++arrows; reach = e; }
else reach = min(reach, (long long)e); // shrink to the common overlap
}
return arrows;
}
The min in the else branch is the part people miss: the arrow must lie inside
every interval it covers, so the reachable point is the smallest end seen so far.
minimum removals?
ASolution
Overlap count is local. Removing a popular interval can leave two others overlapping that a different removal would have separated. Sorting by end and keeping a maximal non-overlapping set is optimal.
Meeting room problems
Minimum rooms equals the maximum number of meetings happening at the same time. A sweep over sorted events computes it directly:
int minRooms(vector<pair<int,int>>& iv) {
vector<pair<int,int>> ev; // {time, delta}
for (auto& [s, e] : iv) {
ev.push_back({s, +1});
ev.push_back({e, -1});
}
sort(ev.begin(), ev.end(), [](auto& a, auto& b) {
if (a.first != b.first) return a.first < b.first;
return a.second < b.second; // end before start on a tie
});
int cur = 0, best = 0;
for (auto& [t, d] : ev) { cur += d; best = max(best, cur); }
return best;
}
The tie-break matters: if one meeting ends at 10 and another starts at 10, they
can share a room, so the -1 must be processed first. With closed intervals
([start, end]), reverse the tie-break.
Assignment with a heap (Meeting Rooms III, “smallest available room”) sorts
meetings by start and keeps a min-heap of (endTime, room). Free every room whose
end is <= start, then assign the smallest free room.
int minRoomsHeap(vector<pair<int,int>>& iv) { // alternative formulation
sort(iv.begin(), iv.end());
priority_queue<int, vector<int>, greater<int>> ends;
for (auto& [s, e] : iv) {
if (!ends.empty() && ends.top() <= s) ends.pop(); // reuse a freed room
ends.push(e);
}
return (int)ends.size();
}
Here the size of the heap is the number of rooms in use at the busiest moment, because a room is popped exactly when it becomes reusable.
but pop only when a room frees up?
ASolution
The heap holds end times of meetings currently in progress. Popping one frees exactly one room; the heap size is the concurrent room count.
Huffman coding
Given symbol frequencies, build a binary prefix code with minimum total encoded length. Repeatedly merge the two least frequent nodes.
struct Node { int freq; char ch; Node *l, *r; };
struct Cmp {
bool operator()(const Node* a, const Node* b) const { return a->freq > b->freq; }
};
Node* huffman(const unordered_map<char,int>& freq) {
priority_queue<Node*, vector<Node*>, Cmp> pq;
for (auto& [c, f] : freq) pq.push(new Node{f, c, nullptr, nullptr});
while (pq.size() > 1) {
Node* a = pq.top(); pq.pop();
Node* b = pq.top(); pq.pop();
pq.push(new Node{a->freq + b->freq, '\0', a, b});
}
return pq.empty() ? nullptr : pq.top();
}
Cost of the code is the weighted path length:
\[ \text{cost} = \sum_i f_i \, \ell_i \]
where \(f_i\) is a symbol’s frequency and \(\ell_i\) its codeword length (its depth in the tree). Merging the two smallest is optimal by an exchange argument: in any optimal tree, the two least frequent symbols are siblings at maximum depth, so they can be swapped down without increasing the cost.
The code is a prefix code: no codeword is a prefix of another, which is why decoding is unambiguous — walk the tree until a leaf.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.62cm, font=\scriptsize\bfseries},
a/.style={->, thick}]
\node[n, fill=blue!12] (r) at (0,0) {100};
\node[n, fill=blue!12] (l) at (-1.3,-0.9) {40};
\node[n, fill=blue!12] (rr) at (1.3,-0.9) {60};
\node[n, fill=green!20] (a1) at (-2.0,-1.8) {15};
\node[n, fill=green!20] (a2) at (-0.6,-1.8) {25};
\node[n, fill=green!20] (b1) at (0.6,-1.8) {20};
\node[n, fill=green!20] (b2) at (2.0,-1.8) {40};
\draw[a] (r) -- node[above left, font=\tiny] {0} (l);
\draw[a] (r) -- node[above right, font=\tiny] {1} (rr);
\draw[a] (l) -- (a1); \draw[a] (l) -- (a2);
\draw[a] (rr) -- (b1); \draw[a] (rr) -- (b2);
\node[font=\scriptsize, anchor=north] at (0,-2.3) {deepest symbols get the longest codes};
\end{tikzpicture}
The same merge rule builds optimal merge patterns (combining sorted files with minimum total work) and optimal alphabetic codes with a different constraint.
tree?
ASolution
They can be placed at maximum depth. Swapping them with the deepest symbols does not increase the weighted path length, and putting them under the same parent is the cheapest way to give both maximum depth.
Greedy versus DP
| Greedy | DP | |
|---|---|---|
| Decision | commit now, never revisit | consider all options |
| Proof | exchange argument | recurrence + induction |
| State | the remaining input | the table |
| Complexity | usually \(O(n \log n)\) | usually polynomial in the state space |
| Failure mode | plausible but wrong on a constructed case | too slow or wrong state |
Decision procedure:
- Write the greedy rule.
- Try to construct a counterexample where taking the best now blocks a better combination.
- If you cannot, try the exchange argument. If the swap is clean, greedy is correct.
- If the counterexample exists, write the DP. The counterexample usually tells you what the state must remember.
Interval scheduling passes step 2 because the earliest-ending interval cannot block anything a later-ending one would allow. 0/1 knapsack fails immediately because “best ratio” ignores that the item is indivisible.
deadlines”. Greedy or DP?
ASolution
Greedy: sort by deadline and take every task that still fits, because an earlier deadline is always at least as urgent. If tasks have durations and values, the problem becomes knapsack-like and needs DP.
Counterexamples to incorrect greedy strategies
- Coin change.
{1, 3, 4}, amount 6. Greedy 4+1+1 = 3 coins; optimal 3+3 = 2. - 0/1 knapsack by ratio. Items
(10, 60),(20, 100),(30, 120), capacity- Ratios 6, 5, 4. Greedy takes 10 + 20 = 160; optimal 20 + 30 = 220.
- Activity selection by shortest duration. Intervals
[0, 10],[9, 11],[10, 12]. Shortest first picks[9, 11]and blocks both others; earliest finish picks[0, 10]then[10, 12]. - Interval covering by leftmost point. Points
{1, 5, 6}with intervals[1, 6],[5, 5]. Covering the leftmost uncovered point first needs two intervals; the optimal also needs two, but a variant with[1, 2]shows the point choice is not arbitrary. - Graph coloring by degree order. Greedy colouring in degree order is not optimal; the chromatic number is NP-hard.
- Scheduling by shortest processing time with weights. Unweighted SPT is
optimal for average completion time; weighted needs the ratio
w/p, and precedence constraints break both.
A counterexample is a complete answer. If an interviewer asks “does greedy work?”, one concrete failing input is worth more than a paragraph of intuition.
ASolution
The ratio says the smallest item is best per unit weight, but capacity left over after taking it cannot be filled as efficiently. The optimum skips it and packs two larger items that together use the capacity exactly.
Bugs and edge cases
- Sort key. Ties need a defined secondary order;
sortis not stable. - Comparator. Strict weak ordering, or the sort can crash.
- Empty input.
INT_MINas a sentinel forlastEndis fine; dereferencing the first interval is not. - Closed versus half-open intervals.
s >= lastEndversuss > lastEnddecides whether touching intervals conflict. - Integer overflow. Sums of costs and weighted path lengths need
long long. - Priority queue comparator.
priority_queueis a max-heap; the comparator must returntruewhenahas lower priority. - Greedy with a global counter. Reset per test case.
- Assuming sorted input. Sort unless the statement guarantees it.
intervals. What is the fix?
ASolution
The overlap test: s >= lastEnd allows touching, s > lastEnd forbids it.
Match the statement’s definition of overlap.
Next: Backtracking and Search (DSA Core #9) — recursion trees, pruning, and where search stops being DP.