AnyLearn
All lessons
Mathintermediate

Matching: Augmenting Paths, Hall, König, and the Assignment Problem

Pair workers with tasks, the most pairs or the cheapest total. Learn why augmenting paths prove a matching is maximum, how Hall's and König's theorems give certificates, how the Hungarian method prices an assignment, and why odd cycles and preferences each change the problem.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

Maximal is not maximum

A matching is a set of edges with no shared endpoint: each vertex is paired with at most one partner. Workers to tasks, students to schools, kidney donors to recipients, and radio channels to transmitters are all matchings once you draw the compatibility graph.

TermMeaning
maximalno edge can be added without breaking the rule
maximumlargest possible number of edges
perfectevery vertex is matched

Greedy picking gives a maximal matching in linear time, and it is never terrible: if MM is maximal and M∗M^* is maximum, then ∣M∗∣≤2∣M∣\lvert M^*\rvert \le 2\lvert M\rvert. Every edge of M∗M^* touches some edge of MM (otherwise it could be added), and each edge of MM has only two endpoints to touch with.

Gotcha: On the path a−b−c−da - b - c - d, greedily taking the middle edge b−cb - c gives a maximal matching of size 1, while {a−b, c−d}\{a - b,\ c - d\} has size 2. The factor of 2 is reached, and no local rule avoids it in general. Getting to the true maximum needs the global idea on the next step.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. Maximal is not maximum

A matching is a set of edges with no shared endpoint: each vertex is paired with at most one partner. Workers to tasks, students to schools, kidney donors to recipients, and radio channels to transmitters are all matchings once you draw the compatibility graph.

TermMeaning
maximalno edge can be added without breaking the rule
maximumlargest possible number of edges
perfectevery vertex is matched

Greedy picking gives a maximal matching in linear time, and it is never terrible: if MM is maximal and M∗M^* is maximum, then ∣M∗∣≤2∣M∣\lvert M^*\rvert \le 2\lvert M\rvert. Every edge of M∗M^* touches some edge of MM (otherwise it could be added), and each edge of MM has only two endpoints to touch with.

Gotcha: On the path a−b−c−da - b - c - d, greedily taking the middle edge b−cb - c gives a maximal matching of size 1, while {a−b, c−d}\{a - b,\ c - d\} has size 2. The factor of 2 is reached, and no local rule avoids it in general. Getting to the true maximum needs the global idea on the next step.

2. Augmenting paths: Berge's lemma

Given a matching MM, an alternating path uses edges that are alternately outside and inside MM. An augmenting path is an alternating path whose two endpoints are both unmatched, so it starts and ends with a non-matching edge and has one more non-matching edge than matching edges.

Flipping it, removing its matching edges and adding the others, gives a valid matching one larger:

M′=M △ P,∣M′∣=∣M∣+1M' = M \,\triangle\, P, \qquad \lvert M'\rvert = \lvert M\rvert + 1

where △\triangle is the symmetric difference. On the path a−b−c−da - b - c - d with M={b−c}M = \{b - c\}, the whole path is augmenting, and flipping it yields {a−b, c−d}\{a - b,\ c - d\}.

Key idea: Berge (1957) proved the converse, which is the useful part: a matching is maximum if and only if it has no augmenting path. So the algorithm is a loop, "find an augmenting path, flip it", and the stopping condition is a proof of optimality. This is the residual-graph idea from network flows, specialised to matchings: the matching edges you flip off are exactly the backward arcs.

3. Bipartite matching is a unit-capacity flow

When the graph is bipartite, the flow reduction from the previous lesson applies directly. Add a source feeding every left vertex, a sink fed by every right vertex, orient compatibility edges left to right, and give every arc capacity 1. By the integrality theorem the maximum flow is integral, so each arc carries 0 or 1, and the arcs carrying 1 between the two sides form a maximum matching. Any max-flow code is therefore a matching solver.

flowchart LR
  S["source s"] --> W1["worker 1"]
  S --> W2["worker 2"]
  S --> W3["worker 3"]
  W1 --> T1["task A"]
  W1 --> T2["task B"]
  W2 --> T1
  W3 --> T2
  W3 --> T3["task C"]
  T1 --> K["sink t"]
  T2 --> K
  T3 --> K

4. Hopcroft-Karp: many short paths at once

Finding one augmenting path per round takes up to ∣V∣/2\lvert V\rvert / 2 rounds of O(∣E∣)O(\lvert E\rvert) each, so O(∣V∣∣E∣)O(\lvert V\rvert\lvert E\rvert). Hopcroft and Karp (1973) cut this to O(∣E∣∣V∣)O(\lvert E\rvert\sqrt{\lvert V\rvert}) by working in phases:

  1. BFS from all unmatched left vertices at once, layering the graph by alternating-path distance, and stop at the first layer containing an unmatched right vertex.
  2. DFS inside the layers to collect a maximal set of vertex-disjoint shortest augmenting paths, and flip them all.
  3. Repeat until BFS finds no augmenting path.

Shortest path length strictly increases each phase, and they proved only O(∣V∣)O(\sqrt{\lvert V\rvert}) phases are needed. It is Dinic's blocking-flow algorithm run on the unit-capacity network above.

import networkx as nx
G = nx.Graph()
left = ["ana", "ben", "cho", "dev"]
G.add_nodes_from(left, bipartite=0)
G.add_edges_from([("ana", "j1"), ("ana", "j2"), ("ben", "j1"),
                  ("cho", "j2"), ("cho", "j3"),
                  ("dev", "j3"), ("dev", "j4")])
M = nx.bipartite.hopcroft_karp_matching(G, top_nodes=left)
print({k: v for k, v in M.items() if k in left})
# {'ana': 'j2', 'ben': 'j1', 'dev': 'j4', 'cho': 'j3'}

The returned dict lists each pair in both directions, so filter to one side.

5. Hall's theorem: when everyone can be matched

Sometimes you need a yes or no answer with a reason: can every left vertex be matched? For a subset SS of the left side, let N(S)N(S) be the set of right vertices adjacent to something in SS. Hall (1935) proved:

the left side X can be fully matched  ⟺  ∣N(S)∣≥∣S∣  for every S⊆X\text{the left side } X \text{ can be fully matched} \iff \lvert N(S)\rvert \ge \lvert S\rvert \ \text{ for every } S \subseteq X

Necessity is obvious: SS cannot be matched into fewer than ∣S∣\lvert S\rvert partners. Sufficiency is the deep part, and it follows from max-flow min-cut: a cut smaller than ∣X∣\lvert X\rvert in the unit network always exposes a violating set SS.

Predict first

Five applicants and five jobs. Applicants 1, 2 and 3 are each qualified only for jobs A and B; applicants 4 and 5 are qualified for every job. Is there a perfect matching, and if not, what is the proof?

In practice: Hall's condition is the certificate a scheduler should report on failure: "these 3 people compete for these 2 slots" is actionable in a way "no solution" is not.

6. König's theorem: matchings and covers

A vertex cover is a set of vertices touching every edge. Each matching edge needs its own cover vertex, so in any graph

ν(G)≤τ(G)\nu(G) \le \tau(G)

where ν\nu is the maximum matching size and τ\tau the minimum cover size. König (1931), and Egerváry in the weighted form the same year, proved that in bipartite graphs the two are equal.

Key idea: This is max-flow min-cut again. A minimum cut in the unit network picks, for each matched pair, the left vertex or the right vertex, and those picks are a vertex cover of size ν\nu. The matching proves no smaller cover exists; the cover proves no larger matching exists.

The equality fails as soon as an odd cycle appears. A triangle has maximum matching 1 (any two edges share a vertex) but minimum cover 2 (one vertex misses the opposite edge). That gap is why general-graph matching needs extra machinery, and why minimum vertex cover is NP-hard in general graphs (it is one of Karp's 21 NP-complete problems, 1972) yet solvable in polynomial time in bipartite ones.

A related consequence, in matrix form: the minimum number of lines (rows or columns) covering every zero of a matrix equals the largest set of independent zeros, which is the step the Hungarian method relies on.

7. Weighted matching: the assignment problem

Now every pair has a cost cijc_{ij}, and you want a perfect matching of minimum total cost: nn workers to nn jobs. Kuhn (1955) published the Hungarian method, named for the König and Egerváry results it builds on; Munkres (1957) showed it runs in polynomial time, and refinements by Tomizawa (1971) and Edmonds and Karp (1972) brought it to O(n3)O(n^3).

Its engine is a pair of price vectors, uu on rows and vv on columns, kept feasible for the dual linear program:

ui+vj≤cijfor all i,j,maximise ∑iui+∑jvju_i + v_j \le c_{ij} \quad \text{for all } i, j, \qquad \text{maximise} \ \sum_i u_i + \sum_j v_j

The reduced cost cij−ui−vjc_{ij} - u_i - v_j is never negative, and the zero-reduced-cost edges are the "tight" ones. The method looks for a perfect matching using tight edges only. When none exists, König's theorem identifies a cover of the tight edges, and the prices shift by the smallest uncovered reduced cost, creating a new tight edge without breaking feasibility.

Key idea: When a perfect matching on tight edges exists, its cost equals ∑ui+∑vj\sum u_i + \sum v_j, the dual objective, so the prices are a certificate of optimality, exactly as a cut certifies a max flow.

8. Solving an assignment in SciPy

SciPy's linear_sum_assignment solves the rectangular assignment problem. Its documentation states it uses a modified Jonker-Volgenant algorithm with no initialisation, following Crouse (2016, IEEE Transactions on Aerospace and Electronic Systems), a shortest-augmenting-path relative of the Hungarian method with the same O(n3)O(n^3) worst case.

import numpy as np
from scipy.optimize import linear_sum_assignment

cost = np.array([[4, 1, 3],     # worker 0
                 [2, 0, 5],     # worker 1
                 [3, 2, 2]])    # worker 2
rows, cols = linear_sum_assignment(cost)
print(cols, cost[rows, cols].sum())        # [1 0 2] 5

rows, cols = linear_sum_assignment(cost, maximize=True)
print(cols, cost[rows, cols].sum())        # [0 2 1] 11
Predict first

Worker 1 has a cost-0 option (job 1), the cheapest entry in the matrix. Does the optimal assignment give worker 1 job 1?

Gotcha: For a non-square matrix, every row or every column is matched, whichever side is smaller; the rest are left out silently. Pad with dummy rows and an explicit "unassigned" cost if leaving someone out should cost something.

9. General graphs: Edmonds' blossoms

Berge's lemma holds in every graph, but searching for augmenting paths breaks in non-bipartite ones. An alternating search can loop around an odd cycle and reach a vertex at both even and odd distance, so the simple layered search misses augmenting paths that exist.

Edmonds (1965, "Paths, Trees, and Flowers") resolved it. When the search finds an odd alternating cycle, a blossom, it contracts the whole cycle into a single vertex and keeps searching. Any augmenting path in the contracted graph lifts back to one in the original, because an odd cycle can always be entered at one vertex and traversed the right way round to exit at another with the alternation intact.

ProblemBipartite graphsGeneral graphs
Max cardinalityHopcroft-Karp, O(∣E∣∣V∣)O(\lvert E\rvert\sqrt{\lvert V\rvert})Micali-Vazirani (1980), same bound
Max weightHungarian, O(n3)O(n^3)Edmonds' weighted blossom algorithm, polynomial
Min vertex coverequals max matching (König)NP-hard

The 1965 paper was also one of the first to argue that "polynomial time" is the right definition of an efficient algorithm.

Gotcha: nx.max_weight_matching solves the general weighted problem and is far slower than a bipartite solver. If your graph is bipartite, use the bipartite tools or linear_sum_assignment.

10. Stable matching is a different question

Everything so far optimises one number: count or total cost. When both sides have preferences and can walk away, the goal changes. A matching is stable if no pair would both rather be with each other than with their assigned partners.

Gale and Shapley (1962, American Mathematical Monthly) proved a stable matching always exists and gave the deferred-acceptance algorithm: proposers propose in preference order, receivers hold their best offer so far and reject the rest, and it ends after at most n2n^2 proposals. The result is the best stable matching for every proposer, and the worst for every receiver.

Maximum matchingAssignment problemStable matching
Inputcompatibility graphcost per pairranked preferences on both sides
Objectivemost pairsleast total costno blocking pair
Standard methodaugmenting pathsHungarian, Jonker-Volgenantdeferred acceptance
Typical usescheduling, coveragelogistics, trackingschool choice, residency match

Roth and Peranson (1999, American Economic Review) describe the redesign of the US National Resident Matching Program around a deferred-acceptance variant, an example of the algorithm running a real market.

Gotcha: A minimum-cost assignment built from preference ranks is usually not stable, and a stable matching is usually not minimum cost. Decide which property the situation actually requires.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A matching M has no augmenting path. What can you conclude?
    • M is maximal but possibly not maximum
    • M is perfect
    • The graph must be bipartite
    • M is a maximum matching, by Berge's lemma
  2. Three applicants are all qualified only for the same two jobs. What does Hall's theorem say?
    • No matching covers all applicants, since that set of 3 has only 2 neighbours
    • A perfect matching exists if the other applicants are flexible enough
    • The matching problem becomes NP-hard
    • Hall's theorem does not apply because the graph has fewer jobs than applicants
  3. Why does König's theorem (max matching = min vertex cover) fail for a triangle?
    • A triangle has no matching at all
    • Its minimum vertex cover is 1
    • Its maximum matching is 1 but every vertex cover needs 2 vertices, because the odd cycle breaks bipartiteness
    • König's theorem only applies to trees
  4. In the Hungarian method, what is a 'tight' edge?
    • An edge whose reduced cost c_ij - u_i - v_j equals zero
    • An edge already in the current matching
    • The cheapest edge in each row
    • An edge that lies on an odd cycle
  5. A hospital wants residents matched so that no resident and hospital would both prefer each other over their assignments. Which method fits?
    • Hopcroft-Karp maximum cardinality matching
    • Gale-Shapley deferred acceptance
    • The Hungarian method on rank costs
    • Edmonds' blossom algorithm

Related lessons

Math
intermediate

Graphs: A Language for Relationships

A graph is two sets and an incidence relation, and that austerity is why the same object models build dependencies, social networks, register allocation and road maps. This lesson covers the structural properties worth knowing, the special families that make hard problems easy, and the line where a small change to a question makes it intractable.

10 steps·~15 min
Math
advanced

Mechanism Design: Engineering the Rules of the Game

Mechanism design runs game theory backwards: pick the outcome you want, then build rules under which self-interested players produce it. This lesson covers the revelation principle, VCG and its blind spots, Myerson's optimal auction, the impossibility theorems that bound the field, and stable matching as used in residency and school-choice markets.

10 steps·~15 min
Math
advanced

Spectral Graph Theory: What the Laplacian's Eigenvalues Reveal

Turn a graph into its Laplacian matrix and its eigenvalues start answering combinatorial questions: how many components, how many spanning trees, how hard the graph is to cut, and where to cut it. Covers the Fiedler vector, Cheeger's inequality, spectral clustering, random-walk mixing, and expanders.

10 steps·~15 min
Math
intermediate

Network Flows: Augmenting Paths and the Max-Flow Min-Cut Theorem

Why pushing flow greedily gets stuck, how the residual graph makes every decision reversible, and why the maximum flow always equals the minimum cut. Build Edmonds-Karp in Python, compare the classic algorithms, and see cuts solve image segmentation and project selection.

10 steps·~15 min