Bipartite Matching
Pairing applicants to jobs, students to slots, files to disks: all are maximum bipartite matching. We solve it combinatorially with augmenting paths (Kuhn's algorithm, ), speed it up to with Hopcroft–Karp, and uncover the structure behind it — König's theorem (max matching equals min vertex cover) and Hall's marriage theorem (a perfect matching exists iff every set has enough neighbors).
╌╌╌╌
A great many assignment problems share one shape: two disjoint groups, a list of
which pairs are compatible, and the wish to pair off as many as possible with no
one used twice. Applicants and jobs, students and exam seats, taxis and riders,
files and disk blocks — each is a bipartite graph, and pair off as many as possible
is maximum bipartite matching. The previous
lesson showed this falls out of max-flow as a
unit-capacity special case. This lesson takes matching on its own terms: a direct
combinatorial algorithm, a faster one, and the two theorems that explain why
the greedy-looking augmenting trick works.
The problem
We restrict to bipartite graphs: splits into two sides and with every edge running between them (, never within a side). The bipartite structure is what makes the problem tractable; matching in general graphs is also polynomial but needs Edmonds' far subtler blossom algorithm, which we set aside.
Augmenting paths
Every matching algorithm is built on the augmenting path, the same idea as in flow but specialized to alternate on and off the matching.
An augmenting path has odd length: free, unmatched edge, matched edge, unmatched edge, , unmatched edge, free. It carries one more unmatched edge than matched edge. So if we flip — delete its matched edges from and add its unmatched ones — we get a new matching with exactly one more edge, and it is still a valid matching because the only vertices whose status changed were the two formerly-free endpoints. This flip is the matching analogue of pushing flow along a residual path.
The whole theory rests on one fact: the absence of augmenting paths certifies optimality.
This is the soundness/completeness split from the foundations. Soundness:
when the algorithm stops (no augmenting path found), Berge's theorem guarantees
the matching really is maximum — an optimal
verdict is never wrong.
Completeness: as long as the matching is suboptimal, an augmenting path
exists to be found, so the algorithm never halts early. Berge's theorem turns
local non-improvability into global optimality.
A trace on one graph
Take a fixed graph on and with edges . Start with the empty matching and process left vertices in order, finding one augmenting path each time. The first two are trivial single edges, because their targets are free; the third forces a genuine re-route.
- : the edge reaches a free right vertex. Augment; .
- : 's only neighbor is taken by . Try to re-route : its other neighbor is free, so the path augments. Flip it: , size .
- : neighbor is taken by ; 's alternate is taken by ; has no other neighbor, so that branch dead-ends. Back at , try its other neighbor — free. Augment ; has size .
- : neighbor is taken by ; 's alternate is taken by ; 's alternate is taken by ; dead-ends. Back at , its other neighbor is free. Augment ; has size .
Every left vertex is matched, so is perfect and certainly maximum. The trace below shows the matching after each augmentation; augment 2 rewires an existing edge rather than merely adding one.
Kuhn's algorithm
Berge's theorem suggests the algorithm immediately: repeatedly find an augmenting path and flip it, until none remains. In a bipartite graph the search is especially clean. Try to match each left vertex in turn. From , run a DFS that only ever takes alternating steps: step to a neighbor ; if is free, we have found the end of an augmenting path — match – and return; if is already matched to some , recursively try to re-route to a different free partner, and if that succeeds, is freed for . This is the Hungarian / Kuhn augmenting-path method.1
- 1foreach dowho is matched to
- 2
- 3foreach do
- 4reset for all
- 5if then
- 6returnand holds the matching
- 7
- 8// try to match (or re-route) along an alternating path
- 9function :
- 10foreach do
- 11if not then
- 12
- 13// free, or its partner can step aside
- 14if or then
- 15
- 16return
- 17return
In practice Kuhn is much faster than the bound: greedily seeding the matching first (match each to any free neighbor before running the loop) and iterating from the higher-degree side both cut the constant sharply. For dense graphs can be , which is why the next algorithm matters.
Hopcroft–Karp
Kuhn finds one augmenting path per phase. Hopcroft–Karp finds a maximal set of shortest, vertex-disjoint augmenting paths per phase, all at once, and augments along all of them simultaneously. The speedup mirrors Edmonds–Karp's BFS choice for flow: forcing shortest augmenting paths makes the shortest length strictly increase across phases, capping the number of phases.2
Each phase has two steps:
- BFS from all free left vertices simultaneously, layering the graph by alternating distance, and stopping at the first layer that contains a free right vertex. This finds the length of the shortest augmenting paths.
- DFS to greedily extract a maximal set of vertex-disjoint augmenting paths of that exact length , flipping each as it is found.
- 1foreach do
- 2foreach do
- 3
- 4while finds at least one augmenting path doone phase
- 5foreach free do
- 6if then
- 7return
- 8
- 9// layer by alternating distance; return true if a free right vertex is reached
- 10function :
- 11empty queue
- 12foreach do
- 13if then ; enqueue
- 14else
- 15
- 16while nonempty do
- 17dequeue
- 18foreach do
- 19left vertex across the matched edge
- 20if thenreached a free right vertex
- 21else if then ; enqueue
- 22return
- 23
- 24// extend one shortest augmenting path from , respecting BFS layers
- 25function :
- 26foreach do
- 27
- 28if or ( and ) then
- 29;flip this edge
- 30return
- 31dead end; never revisit
- 32return
For dense bipartite graphs this is a real gain over Kuhn's , and Hopcroft–Karp is the standard choice when is large. It is also Dinic's algorithm specialized to unit-capacity bipartite networks — the bound is Dinic's on such networks.
König's theorem
Augmenting paths solve the matching problem; the next two theorems explain its structure, and both are good interview material in their own right. The first links matching to its natural dual, the vertex cover.3
Any matching and any vertex cover are tied by an easy inequality: a vertex cover must contain at least one endpoint of every matched edge, and those endpoints are all distinct (matching edges are disjoint), so always — this is weak duality, exactly as was for flow. König's theorem says that in bipartite graphs the bound is tight.
The construction doubles as an algorithm for the minimum vertex cover. Run Kuhn or Hopcroft–Karp, then one alternating-reachability BFS from the free left vertices computes and reads off . So minimum vertex cover — NP-hard in general graphs — is polynomial on bipartite graphs, solved through matching. By complementation, is a maximum independent set, also polynomial here.
Hall's marriage theorem
The second structural result answers a different question: not how large is the matching, but when does it saturate one whole side. Picture as people and as the partners they would accept; we want everyone in married. The obstruction is obvious once stated: if some set of people collectively know fewer than acceptable partners, they cannot all be matched. Hall's theorem says this single obstruction is the only one. Write for the set of neighbors of (every -vertex adjacent to some vertex of ).
Hall's theorem is the existence companion to König's optimization statement; the proof above derives one directly from the other. A corollary handles the symmetric, fully-balanced case:
This corollary explains why a -regular bipartite graph's edges decompose into perfect matchings (peel one off, repeat), which underlies, e.g., scheduling conflict-free rounds.
The reduction to max-flow
The combinatorial view and the flow view describe the same object. The max-flow reduction makes this explicit, and it is worth carrying out once in full because it explains where the augmenting-path machinery comes from.
Given a bipartite graph , build a flow network :
- add a source and a sink ;
- for each , an edge of capacity ;
- for each original edge , a directed edge of capacity (direction to );
- for each , an edge of capacity .
Every capacity is . An integer – flow of value then corresponds exactly to a matching of size : the unit capacity on lets at most one middle edge out of carry flow, and the unit capacity on lets at most one into , so the saturated middle edges form a set of disjoint pairs — a matching. Conversely a matching of size routes units. Because all capacities are integral, the integrality theorem for max-flow guarantees an integer maximum flow exists, so max-flow value maximum matching size.
An augmenting path in this network alternates forward edges (unused) with backward residual edges (used) — and on the middle layer that is precisely an alternating path in : a forward is an unmatched edge, a backward is a matched edge traversed in reverse. Kuhn's DFS is the flow algorithm with the and plumbing stripped away, and Hopcroft–Karp is Dinic on this same network. The two views are the same algorithm in different notation.
Why not just call max-flow?
Matching reduces to flow, but the dedicated combinatorial algorithms are still worth having, for several reasons.
- Simplicity and constants. Kuhn is a dozen lines of DFS with no residual bookkeeping, no source/sink scaffolding, and tiny constants — the practical default for the moderate sizes seen in contests and interviews.
- The right asymptotics. Hopcroft–Karp's matches the best general bound for this problem and beats a black-box Edmonds–Karp ( is far worse here); you get the specialized bound without invoking Dinic by hand.
- Structure, not just a number. König and Hall fall straight out of the augmenting-path picture, yielding minimum vertex cover, maximum independent set, and saturation certificates — outputs the flow value alone does not give.
The flow reduction remains the right tool the moment the problem stops being pure matching: capacities other than (a job hiring several applicants), costs on edges (minimum-cost assignment), or many-to-one constraints. Matching is the special case; flow is the generalization for anything beyond it.
Weighted, general, and online matching
Unweighted bipartite matching is the entry point to a larger theory; three generalizations are worth knowing by name.
Weighted matching — the assignment problem. Put a cost on each edge and ask for the cheapest perfect matching: this is the assignment problem, solved by the Hungarian algorithm (Kuhn 1955, from Kőnig's and Egerváry's ideas) in .4 It maintains dual variables (potentials
) on the vertices and augments along shortest alternating paths — structurally the same augmenting-path idea, now weighted, and equivalent to min-cost max-flow specialized to unit capacities. It is the standard method for optimal task-to-worker, sensor-to-target, and tracking-association assignments.
General graphs — Edmonds' blossoms. Drop the bipartite restriction and the augmenting-path method breaks, because an odd cycle can hide an augmenting path that alternating BFS never finds. Edmonds' blossom algorithm (1965) repairs this by contracting each odd cycle (a blossom
) into a single vertex, searching the smaller graph, then lifting the result back — and in doing so gave the field its working definition of efficient
as polynomial time.5 Micali and Vazirani later pushed general matching to , matching the bipartite bound.
Online and streaming. When one side arrives over time and must be matched irrevocably on arrival — ad impressions to advertisers, riders to drivers — no algorithm can match the offline optimum. The RANKING algorithm (Karp, Vazirani, Vazirani 1990) fixes a random priority over the offline side and greedily matches each arrival to its highest-priority free neighbor, achieving a competitive ratio of , which is provably optimal for online bipartite matching.6 This result launched the whole field of online matching that underlies modern ad-allocation systems.
All three build on the augmenting path from this lesson: weighted matching augments with costs, general matching augments through contracted blossoms, and online matching gives up augmentation entirely for a randomized greedy rule.
Takeaways
- A matching is a set of pairwise-disjoint edges; in a bipartite graph we want a maximum one, and the whole theory turns on the augmenting path (alternating, free-to-free), whose flip grows by one.
- Berge's theorem: is maximum iff it has no augmenting path — the soundness (stops only at optimum) and completeness (always improvable until optimum) of every augmenting-path algorithm.
- Kuhn's augmenting-path DFS runs in ; Hopcroft–Karp batches shortest, disjoint augmenting paths per phase for , the unit-capacity specialization of Dinic.
- König's theorem: in bipartite graphs max matching min vertex cover, giving a polynomial minimum vertex cover (NP-hard in general) and, by complement, maximum independent set.
- Hall's marriage theorem: is fully matchable iff for all ; it yields perfect matchings for -regular bipartite graphs and is König's dual face.
Footnotes
- CLRS, Ch. 26 — Maximum Flow: bipartite matching as unit-capacity flow, and the augmenting-path method underlying Kuhn's algorithm. ↩
- Erickson, Ch. 11 — Applications of Maximum Flow: matching, vertex cover, and the shortest-augmenting-path speedup behind Hopcroft–Karp / Dinic. ↩
- Skiena, §6 — Weighted Graph Algorithms: bipartite matching in practice, and the matching / vertex-cover duality (König). ↩
- Kuhn, H. W. (1955),
The Hungarian method for the assignment problem,
Naval Research Logistics Quarterly 2, 83–97 — minimum-cost perfect matching via vertex potentials. ↩ - Edmonds, J. (1965),
Paths, trees, and flowers,
Canadian Journal of Mathematics 17, 449–467 — the blossom algorithm for maximum matching in general graphs. ↩ - Karp, R. M., Vazirani, U. V. & Vazirani, V. V. (1990),
An optimal algorithm for on-line bipartite matching,
Proc. STOC 1990, 352–358 — the RANKING algorithm and its competitive ratio. ↩
╌╌ END ╌╌