←All posts

The Gale–Shapley Algorithm — Why Deferring Acceptance Produces Stable Matchings, Shown by Running It

Deferred acceptance, the Gale–Shapley algorithm behind residency matches and school choice, always stops at a stable matching, and the one it returns is the best stable matching for the proposing side. Proofs and interactive demos show why, and cover the lattice of stable matchings, strategic misreporting, random markets and the many-to-one extension.

AlgorithmsStable MatchingMarket DesignGame TheoryInteractive

Every autumn, final-year medical students in Japan submit a list of the hospital training programs they want, in order of preference, and the hospitals submit lists of the students they want to hire. A computer decides who goes where, and everyone learns the result on the same day. This is the Japan Residency Matching Program (JRMP). At the heart of the procedure is deferred acceptance — the Gale–Shapley algorithm that David Gale and Lloyd Shapley described in a seven-page paper in 1962.

The algorithm fits in about twenty lines, and the following properties have been proved about it.

  • A stable matching always exists, and one can be found in O(n2)O(n^2) time.
  • The result does not depend on the order of proposals, and it is the best stable outcome for the side that proposes and the worst for the side that receives.
  • Proposers cannot gain by misreporting their preferences. Receivers sometimes can.
  • With random preferences, proposers end up with an average rank of about ln⁡n\ln n and receivers with about n/ln⁡nn / \ln n — a big gap. Yet adding a single agent to one side makes it almost irrelevant who proposes: the short side gets an average rank of about ln⁡n\ln n either way.

The original paper and many textbooks describe the algorithm with the metaphor of men proposing marriage to women. This article uses the gender-neutral terms proposers and receivers. The agents on the left are A, B, C, D and those on the right are W, X, Y, Z. It may help to read the left side as residents, students or applicants, and the right side as hospitals, schools or employers.

For just the algorithm and its implementation, read sections 1.1–1.2, 3, 4.5 and 10. Sections 4–5 explain why it works and which stable matching it returns, section 6 covers misreporting, section 7 random markets, section 8 real market design, and section 9 variants and hardness. Collapsed proofs and deep dives can be skipped without losing the thread. Key terms and the sections that define them: blocking pair (1.2), deferred acceptance (section 3), valid partner (5.2), rotation (5.4–5.5), truncation (6.2), individual rationality (8.1) and cutoff (8.4).

Watch the video explainer4:22Synthesized narration · burned-in captions
Show transcript

Can ordered preference lists alone produce a matching that will not fall apart? Let's unpack Gale-Shapley deferred acceptance, the idea behind residency matching and school choice.

Agents on the two sides rank everyone on the other side, from best to worst. The goal is not merely to pair everybody up. If two agents who aren't paired together both prefer each other to their current partners, they form a blocking pair. A matching with no blocking pair is called stable.

Stability means no pair has an incentive to make a side deal outside the system. In the US residency market of the 1940s, appointments moved almost two years before graduation. Reply deadlines then shrank from ten days to roughly twelve hours. A centralized match introduced in 1952 ended the chaos; Roth later argued it worked because its outcomes were stable.

So can we simply fix one blocking pair whenever we see it? Unfortunately, local repair can cycle. In a three-by-three example, four valid repairs bring the matching right back to the start. What we need is not ad hoc repair, but a global procedure.

In deferred acceptance, proposers apply in order, starting with their favorite receivers. Each receiver tentatively holds only the best proposal it has seen so far. If a better proposal arrives later, the receiver trades up and releases the old proposer. That deferral is the decisive difference from immediate acceptance, also called the Boston mechanism.

In the article's running example, A through D propose to W through Z. B, C, and D all rank the popular Z first. Z trades up from B to C, then to D; the displaced B then moves on to W. After seven proposals, A pairs with X, B with W, C with Y, and D with Z.

Two monotonic facts make the algorithm work. Receivers only trade up, while proposers only move down their own lists. Because no proposer applies to the same receiver twice, the procedure must stop. For complete n-by-n lists, the sharper bound is n squared minus n plus one proposals. If a blocking pair existed, the receiver rejected that proposer earlier and later held someone it likes more — a contradiction.

The output does not depend on the order in which proposals are processed. That is because every proposer gets its best partner among all stable matchings. The same outcome is the receivers' worst stable outcome. The running example has four stable matchings, forming a diamond-shaped lattice from the proposer-optimal to the receiver-optimal one.

The same asymmetry appears in incentives. For proposers, reporting true preferences is a dominant strategy. Receivers, however, can sometimes gain by truncating their lists. But with everyone else truthful, only a receiver whose partner differs across stable matchings can gain. No mechanism can always be stable and make truth-telling best for everyone.

In random markets, the expected number of proposals is at most n times the nth harmonic number. So it is about n log n, far below the quadratic worst case. In a balanced market, proposers' average rank is about log n, receivers' about n divided by log n. But with just one extra agent on one side, the short side has an average rank of about log n no matter who proposes.

Real residency matching is many-to-one: a hospital can have several positions. Deferred acceptance extends by letting each hospital hold its best applicants up to its quota. The rural hospitals theorem says an under-filled hospital receives the same residents in every stable matching. Outcomes can also be explained with cutoffs: the lowest-ranked applicant each full hospital admitted.

Deferred acceptance works because the best current offer is held, not finalized, until the end. That small difference delivers stability, proposer-optimality, and truthful reporting for proposers. The article lets you explore blocking pairs, the algorithm, lattices, strategy, and random markets through interactive demos.

1. The problem: matching when both sides have preferences

1.1 Setting

There is a set LL on the left and a set RR on the right; for now both have nn members. Every agent ranks everyone on the other side strictly, with no ties. We write a≻xba \succ_x b when xx prefers aa to bb.

A matching μ\mu is a set of left–right pairs in which each agent appears in at most one pair. We write μ(x)\mu(x) for xx's partner.

Throughout the article we use the following 4-by-4 «running example».

AgentPreferences (best first)
AW > X > Z > Y
BZ > W > Y > X
CZ > Y > W > X
DZ > X > Y > W
WC > B > D > A
XD > B > A > C
YB > C > D > A
ZA > D > C > B

B, C and D all list Z first, so in this example they compete for Z.

1.2 Blocking pairs and stability

Given a matching μ\mu, two agents (a,w)(a, w) from opposite sides who are not matched to each other form a blocking pair if

w≻aμ(a)anda≻wμ(w).w \succ_a \mu(a) \quad \text{and} \quad a \succ_w \mu(w).

Both of them prefer each other to their current partners. An agent without a partner is assumed to prefer any partner to none (we drop this assumption for truncated reports in section 6 and in general in section 8).

A matching with no blocking pair is called stable.

Take, for example, the matching A–W, B–X, C–Y, D–Z (written «AW BX CY DZ» from now on). B prefers W (its 2nd choice) to its partner X (4th), and W prefers B (2nd) to its partner A (4th). So (B,W)(B, W) is a blocking pair, and this matching is not stable.

1.3 Why ask for stability?

The two agents of a blocking pair have a reason to ignore the assignment and make a deal on their own. Once one such side deal happens, the rest of the assignment can unravel. Stability is the condition under which nobody has an incentive to trade outside the system — the condition under which an assignment is actually honored.

In the 1940s, US hospitals competing for good students kept moving their offers earlier, until appointments were being made nearly two years before graduation. When the medical schools agreed in 1945 to hold back transcripts and letters until a fixed date, the competition simply moved to deadlines: offers were supposed to stay open for 10 days in 1945, and the interval shrank every year until, by 1949, even a 12-hour grace period was rejected as too long (Roth, 1984). These were «exploding offers» that had to be answered before hanging up the phone. A centralized match (today's NRMP) was introduced in 1952, the chaos subsided, and participants voluntarily stayed with it.

Alvin Roth (1984) pointed out that the procedure in use since 1952 produced stable matchings, and argued that this was why it succeeded. Roth (1991) then compared the regional residency matches of the United Kingdom and found that the schemes producing stable matchings survived, while most of those that did not were abandoned.

1.4 Why not maximize total satisfaction?

One could convert preferences into scores and maximize «total satisfaction» — solve an assignment problem with the Hungarian method, say. That solution need not be stable. In the running example, minimizing just the left side's total rank gives AW BZ CY DX (total 6), but (C,Z)(C, Z) and (D,Z)(D, Z) are blocking pairs. Minimizing the total rank of both sides happens to pick two of the stable matchings in the running example (AZ BW CY DX and AZ BY CW DX, the «egalitarian» ones of section 5.5), but that is not guaranteed either: on randomly generated 4-by-4 instances, roughly one time in four every matching with the minimum two-sided total rank is unstable. Stability is a condition about each participant's incentives — nobody wants to defect — rather than about a sum, and it is defined from rankings alone, without assuming numeric utilities. Both properties make it practical.

2. The naive approach: fix unhappy pairs one at a time

The most naive way to build a stable matching is to start from any matching and, while a blocking pair exists, let those two pair up. If we also pair up the two partners they abandoned, everybody keeps a partner.

This procedure does not always end. Try it in the demo below. It starts with a 3-by-3 example. Click a preference chip to rearrange the matching by hand; blocking pairs show up as red dashed lines.

Hunting blocking pairs — and how fixing them one at a time can cycle

Click chips to rearrange the matching; blocking pairs appear as red dashed lines. Resolving one pairs those two up and pairs their abandoned partners with each other.

Instance
A–C· click to pair
A
B
C
AXBYCZ
X–Z· click to pair
X
Y
Z
2 blocking pairs
  • (C, Y) C prefers Y (#1) to its partner Z (#3), and Y prefers C (#2) to its partner B (#3).
  • (C, X) C prefers X (#2) to its partner Z (#3), and X prefers C (#1) to its partner A (#2).
Actions

The scenario resolves (C, X) → (C, Y) → (A, Y) → (A, X), each a genuine blocking pair at that moment. After four moves it is back where it started.

Matchings visited
AX BY CZ

Press «Cycle scenario» four times. It resolves (C,X)→(C,Y)→(A,Y)→(A,X)(C, X) \to (C, Y) \to (A, Y) \to (A, X), each a genuine blocking pair at that moment, and yet it arrives back at the starting matching AX BY CZ. As long as pairs are chosen this way, the procedure never ends. Knuth (1976) pointed out that resolving blocking pairs can cycle.

If instead (C,Y)(C, Y) is chosen at the start, a single step reaches the stable matching AX BZ CY. Roth and Vande Vate (1990) showed that from any matching, a well-chosen finite sequence of resolutions reaches a stable matching, and that choosing blocking pairs at random reaches one with probability 1 (in their model, abandoned partners become single). The random approach can, however, need exponential expected time on some instances (Ackermann et al., 2011).

Switch the demo to «Running example (4×4)» and it starts from AW BX CY DZ, the matching of section 1.2, with two blocking pairs, (B,W)(B, W) and (B,Y)(B, Y). Resolving (B,W)(B, W) pairs up the abandoned A and X and reaches AX BW CY DZ in one step — exactly the stable matching Gale–Shapley returns in the next section.

So fixing blocking pairs one at a time may never finish, depending on which pairs are chosen. The Gale–Shapley algorithm of the next section is a procedure that always stops and returns a stable matching, whatever order it runs in.

3. The Gale–Shapley algorithm (deferred acceptance)

3.1 The procedure

Call one side (here the left) the proposers and the other side the receivers.

start with everyone free (unmatched)
while some proposer p is free and still has someone left to propose to:
    r ← the receiver p likes best among those p has not proposed to yet
    p proposes to r
    if r holds nobody:
        r holds p «tentatively»
    else if r prefers p to the proposer p' it currently holds:
        r holds p and lets go of p' (p' becomes free)
    else:
        r rejects p
finalize the pairs currently held and stop

Two rules drive the procedure. Proposers propose one at a time, in order of preference, moving on when rejected. Receivers hold only the best proposal received so far and reject the rest. Holding is not a commitment: if a better proposal arrives later, the receiver trades up.

3.2 Running it

Step through the running example in the demo below. The tables on both sides show each agent's preferences; a chip's look tells you whether it is part of the current proposal (amber), next to be proposed to (dashed amber), tentatively held (gray), rejected or turned away (struck through) or in the final result (green). The «#k» at the end of each row is the position of that agent's current partner in its own list (a proposer without a partner shows «→#k», the position of its next proposal). Before pressing play, try to predict whom B ends up with.

Gale–Shapley deferred acceptance, one move at a time

Switch the proposing side, the proposal order and the acceptance rule, then play. Click any chip in a list to move it up one place and edit preferences.

Instance
Who proposes
Acceptance
Proposal order
A–D· proposers
A:
W
→#1
B:
Z
→#1
C:
Z
→#1
D:
Z
→#1
AWBXCYDZ
W–Z· receivers
W:
C
–
X:
D
–
Y:
B
–
Z:
A
–
proposal in this stepnext proposaltentatively held (may still change)×rejected / droppedfinal resultblocking pair left in the result#krow end: rank of the current partner (grows for proposers, shrinks for receivers)
What happened

Everyone starts free. The proposers (A–D) propose down their lists from the top. Each receiver tentatively holds the best offer so far and rejects the rest.

Tally
Proposals so far: 0 / bound 13 (n²−n+1)
Current pairs: A– B– C– D–
1 / 8

In the running example (A–D propose, one at a time) the algorithm stops after these seven proposals.

  1. A → W (1st choice). W is free and holds A tentatively.
  2. B → Z. Z is free and holds B tentatively.
  3. C → Z. Z ranks A > D > C > B, so it lets B go and trades up to C. B is free again.
  4. D → Z. Z prefers D to C, so it lets C go and trades up to D. C is free again.
  5. B → W (2nd choice). W ranks C > B > D > A, so it lets A go and trades up to B. A is free again.
  6. C → Y (2nd choice). Y is free and holds C.
  7. A → X (2nd choice). X is free and holds A. Everyone has a partner, so the algorithm stops.

The result is AX BW CY DZ, with no blocking pair. In steps 3–5, B, pushed out of the contest for Z, proposes to W and in turn pushes out A, whom W had been holding. Each time a receiver trades up, the proposer it drops proposes to its next choice, and the chain continues.

3.3 What if acceptance is not deferred?

Switch the demo's «Acceptance» setting to «Immediate (Boston)». Under immediate acceptance, in round kk every unassigned proposer applies to their kk-th choice, and receivers make their acceptance final on the spot. A better proposal arriving later cannot change it.

The running example now ends in AW BX CY DZ, leaving (B,W)(B, W) and (B,Y)(B, Y) as blocking pairs. In round 1, B applied to the popular Z and was rejected — and meanwhile W permanently accepted A, whom W ranks last. W prefers B to A but no longer has a seat.

Because Boston's public schools once used this rule, it is called the «Boston mechanism». The «deferred» in deferred acceptance refers exactly to this: postponing commitment until the very end. The difference also decides whether truthful reporting is the best strategy (section 6.4).

3.4 The order of proposals does not matter

Now switch the demo's «Proposal order». «All at once (rounds)» is how Gale and Shapley wrote it: in each round every free proposer proposes simultaneously and each receiver keeps only its best offer. The running example finishes in three rounds. «Queue», «Stack» and «Random» all pick one free proposer at a time, the version common in algorithms textbooks; the stack version, in which a proposer who becomes free proposes again immediately, corresponds to the chain-reaction formulation of McVitie and Wilson (1971).

Whatever the order, the final result stays AX BW CY DZ and the number of proposals stays 7. Section 5 proves that this always holds.

4. Why it works

4.1 Two monotonicity properties

The proofs need only two facts that are visible directly in how the algorithm behaves.

  • Receivers only get better: once a receiver has received a proposal, it holds someone for the rest of the run, and every trade-up gives it someone it likes more.
  • Proposers only get worse: each proposer works down its own list. It never proposes to the same receiver twice, and each proposal goes to someone it likes less than the last.

The «#k» at the end of each row in the demo of section 3.2 shows this directly: proposers' numbers only grow and receivers' numbers only shrink.

4.2 Termination: at most n2−n+1n^2 - n + 1 proposals

Each proposer proposes to each receiver at most once, so there are at most n2n^2 proposals and the algorithm always stops. We can count more precisely.

Everyone is matched exactly when the last receiver receives its first proposal (by monotonicity, a receiver that has been proposed to keeps holding someone, so once every receiver has been proposed to, everyone has a partner). Until just before that moment, at least one receiver r∗r^* has not been proposed to by anyone. So each proposer has made at most n−1n - 1 proposals so far, for at most n(n−1)n(n-1) in total. Adding the final proposal,

number of proposals≤n(n−1)+1=n2−n+1.\begin{aligned} \text{number of proposals} &\le n(n-1) + 1 \\ &= n^2 - n + 1. \end{aligned}

This bound is attained exactly. The «Worst case» preset of the demo in section 3.2 is a 4-by-4 instance that needs 13 proposals. «Identical lists» (every proposer ranks W > X > Y > Z), the most competitive case, still falls short of the worst case: everybody proposes to W, one of them stays, the rest propose to X, and so on, so it takes only 4+3+2+1=104 + 3 + 2 + 1 = 10 proposals whatever the receivers' preferences. The minimum is n=4n = 4, reached whenever all first choices differ (for example when W–Z propose in section 5.1). Since the demo lets you edit any list by clicking its chips, try starting from the running example and see how high you can push the number of proposals.

4.3 Everyone gets a partner

Suppose some proposer pp is still free at the end. A proposer stops free only after proposing to everyone on its list. Then every receiver has been proposed to at least once, so every receiver holds someone. If the nn receivers each hold a different proposer, all nn proposers are held — contradicting the fact that pp is free.

4.4 Stability

Suppose the output μ\mu had a blocking pair (p,r)(p, r). Since r≻pμ(p)r \succ_p \mu(p) and pp proposes in order of preference, pp proposed to rr before μ(p)\mu(p). They did not end up together, so at some point rr rejected pp (immediately, or later by trading up). At that point rr held someone it liked more than pp, and since receivers only get better, its final partner μ(r)\mu(r) is also someone it likes more than pp. That contradicts p≻rμ(r)p \succ_r \mu(r).

4.5 Running time and implementation essentials

If each proposal is processed in O(1)O(1) time, the whole run takes O(n2)O(n^2). The key is to convert the receivers' preferences into a rank table first.

  • rank[r][p]: the position of pp in receiver rr's list. «Does rr prefer pp or p′p'?» takes two array lookups.
  • next[p]: the position in pp's list of the next receiver to propose to.
  • Keep the free proposers in a queue or a stack.

Without a rank table, finding «where is pp in this list?» by linear search makes each comparison O(n)O(n) and the whole algorithm O(n3)O(n^3).

The input itself (2n2n lists of length nn) has size Θ(n2)\Theta(n^2), so O(n2)O(n^2) is linear in the size of the input. And it cannot be done faster: measured by the number of queries to the preference lists, finding a stable matching needs Ω(n2)\Omega(n^2) queries in the worst case (Ng and Hirschberg, 1990). Similar lower bounds hold for randomized algorithms and for communication (Gonczarowski et al., 2019). A Python implementation and tests are in section 10.

5. Which stable matching, and good for whom?

5.1 There can be more than one stable matching

Let the receivers (W–Z) propose in the running example. The run ends after four proposals — W→C, X→D, Y→B, Z→A — and the result is AZ BY CW DX. Every receiver gets its first choice, while A, B and C get their 3rd choice and D its 2nd. This matching is stable too. So the result depends on which side proposes. Which of the stable matchings, then, does Gale–Shapley return?

5.2 Proposer-optimality

If a proposer pp and a receiver rr are paired in at least one stable matching, call rr a valid partner of pp. Write best(p)\mathrm{best}(p) for pp's favorite valid partner.

The running example has four stable matchings (section 5.4), and the proposers' valid partners are as follows (best(p)\mathrm{best}(p) in bold).

ProposerValid partners (best first)
AX (2nd choice), Z (3rd choice)
BW (2nd choice), Y (3rd choice)
CY (2nd choice), W (3rd choice)
DZ (1st choice), X (2nd choice)

Collecting everyone's best\mathrm{best} gives AX BW CY DZ — exactly the output of section 3.2. Each proposer takes its own favorite, and yet no two of them want the same partner. That is what the next theorem says.

Theorem (Gale–Shapley, 1962). In the output of proposer-proposing Gale–Shapley, every proposer pp is matched to best(p)\mathrm{best}(p).

Proof. Suppose that during the run some proposer is rejected by a valid partner, and consider the first time this happens. Receiver rr rejects pp, of whom it is a valid partner, in favor of p′p' (so p′≻rpp' \succ_r p). Since rr is a valid partner of pp, there is a stable matching SS that pairs pp with rr. Let r′r' be p′p''s partner in SS.

Because p′p' is now proposing to rr (or being held by it), every receiver above rr on p′p''s list has already rejected p′p'. Since we are looking at the first rejection by a valid partner, none of those rejections came from a valid partner of p′p'. But r′r' is a valid partner of p′p' (they are paired in SS), so r′r' is not above rr: we have r≻p′r′r \succ_{p'} r'.

Now in SS, p′p' prefers rr to its partner r′r', and rr prefers p′p' to its partner pp. So (p′,r)(p', r) blocks SS, contradicting the stability of SS. Hence no proposer is ever rejected by a valid partner. In particular pp is never rejected by best(p)\mathrm{best}(p), so it ends with someone at least as good as best(p)\mathrm{best}(p). On the other hand, the output is stable (section 4.4), so that final partner is a valid partner and cannot be better than best(p)\mathrm{best}(p). Hence pp is matched with best(p)\mathrm{best}(p). ■\blacksquare

This theorem explains every observation in section 3.4.

  • The output is exactly «everyone matched with best(p)\mathrm{best}(p)», so it does not depend on the order of proposals.
  • Each pp proposes exactly once to each receiver it ranks at or above best(p)\mathrm{best}(p), so the set of proposals does not depend on the order either, and their number equals the sum of the proposers' final ranks: 2+2+2+1=72 + 2 + 2 + 1 = 7 in the running example.

Roth (1982) also showed that no matching at all — stable or not — makes every proposer strictly better off than the proposer-optimal stable matching.

5.3 Receiver-pessimality

Theorem. In the same output, every receiver is matched to the valid partner it likes least.

Proof. Suppose that in the output μ0\mu_0 receiver rr is matched with pp, while in some stable matching SS it is matched with p′′p'', whom it likes less (p≻rp′′p \succ_r p''). In SS, pp's partner is a valid partner other than rr, so proposer-optimality gives r=best(p)≻pS(p)r = \mathrm{best}(p) \succ_p S(p). Then (p,r)(p, r) blocks SS, a contradiction. ■\blacksquare

So being on the proposing side is an advantage in itself.

Intuitively, proposers start at the top and give up on a receiver only once it is out of reach in every stable matching — exactly what the proof in section 5.2 shows. Receivers can only choose among the offers that arrive; they have no way to court someone who never proposes. It is the logic of an ascending auction: bidders raise their bids only when outbid, so the auction stops at the lowest market-clearing prices — the outcome best for the buyers (Demange, Gale and Sotomayor, 1986).

In the US residency match it later came to light that the procedure used since 1952 produced the same result as a hospital-proposing algorithm; together with students' dissatisfaction, this led to the 1998 switch to an applicant-proposing design (the Roth–Peranson algorithm).

5.4 The lattice of stable matchings

The set of all stable matchings has the following structure.

Opposition of interests. For two stable matchings μ\mu and μ′\mu', if every proposer likes μ\mu at least as much as μ′\mu', then every receiver likes μ′\mu' at least as much as μ\mu.

A lattice. Given two stable matchings μ\mu and μ′\mu', give each proposer the better of its two partners: the result is again a matching, and a stable one. Giving each proposer the worse of the two also yields a stable matching. With these two operations as join and meet, the stable matchings form a distributive lattice. Knuth (1976) credits this result to John Conway. The top of the lattice is proposer-optimal (the output of Gale–Shapley with the left proposing) and the bottom is receiver-optimal (the output with the right proposing).

The demo below checks all 4!=244! = 24 perfect matchings by brute force, keeps the stable ones and draws them ordered by «every left agent weakly prefers» (a Hasse diagram).

The lattice of stable matchings — the two sides' interests are opposed

All 4! = 24 perfect matchings are checked by brute force; the stable ones are drawn in the order “every left agent weakly prefers” (a Hasse diagram). Higher is better for A–D, lower is better for W–Z. Click a node for details; edge labels ρ are rotations.

Instance
Click to
▲ better for A–D4 stable of 24
ρ1ρ2ρ2ρ1AX BW CY DZΣ 7 / 9AX BY CW DZΣ 9 / 7AZ BW CY DXΣ 9 / 6AZ BY CW DXΣ 11 / 4
▼ better for W–ZΣ left rank sum / right rank sum
Selected matching
AX BW CY DZ
pairleft rankright rank
A–X23
B–W22
C–Y22
D–Z12
Σ79
  • ● A–D-optimal (Gale–Shapley output when A–D propose)
  • ● minimum regret (minimum worst rank)
  • ● sex-equal (minimum gap between rank sums)
Rotations (edge labels)
  • ρ1: B W→Y, C Y→W
  • ρ2: A X→Z, D Z→X

A rotation shifts a few left agents around a cycle, each to the partner of the next one: every one of them loses a little and every right agent involved gains a little.

The running example has four stable matchings forming a diamond.

  • Top: AX BW CY DZ (left rank sum 7, right 9)
  • Middle: AX BY CW DZ (9 / 7) and AZ BW CY DX (9 / 6)
  • Bottom: AZ BY CW DX (11 / 4)

The edge labels ρ1,ρ2\rho_1, \rho_2 are operations called rotations. ρ1\rho_1 has B and C swap partners (B: W→Y, C: Y→W) and ρ2\rho_2 has A and D swap partners (A: X→Z, D: Z→X). The two are independent, so applying them in either order reaches the bottom, which is why the diagram is a diamond.

Set the demo's «Click to» control to «Pick two for join / meet» and click the two middle matchings one after the other. From AX BY CW DZ and AZ BW CY DX, giving each left agent the better of its two partners produces the top AX BW CY DZ, and giving it the worse produces the bottom AZ BY CW DX. Both are genuine one-to-one matchings, and both are stable.

Switch to «4×4 maximum (10)» to see a more complex lattice with 10 stable matchings and 12 edges. It is three diamonds stacked on top of each other. There are six rotations in three layers of two. The two rotations in a layer are independent, and both must be applied before the next layer becomes available. Exactly 10 sets of «already applied» rotations are allowed, and they correspond to the 10 stable matchings.

Ten is known to be the maximum for 4-by-4 instances (see the table in Thurber, 2002). In general the number of stable matchings can grow exponentially in nn (Irving and Leather (1986) construct instances with about 2.28n2.28^n stable matchings when nn is a power of 2), while it is also bounded above by cnc^n (Karlin, Oveis Gharan and Weber, 2018). With uniformly random preferences, on the other hand, the expected number of stable matchings is only about e−1nln⁡ne^{-1} n \ln n (Pittel, 1989) — plugging n=100n = 100 into the asymptotic formula gives about 170.

5.5 Rotations and «fair» stable matchings

A rotation, applied to a stable matching μ\mu, shifts a few proposers around a cycle, each moving to the partner of the next one. Every proposer that moves loses a little, and every receiver involved gains a little.

Finding rotations by hand (click to open)

Walk down proposer pp's list below μ(p)\mu(p) and let s(p)s(p) be the first receiver that prefers pp to its current partner; let next(p)\mathrm{next}(p) be that receiver's current partner. Following p→next(p)→⋯p \to \mathrm{next}(p) \to \cdots eventually closes a cycle; that cycle is a rotation, and «applying» it moves each pp in the cycle to s(p)s(p) (a walk that reaches someone with no s(p)s(p) is a dead end; if no walk closes a cycle, μ\mu is the bottom). Checking this at the top of the running example, AX BW CY DZ:

  • Below X on A's list, Z prefers A to its partner D, so s(A)=Zs(A) = Z and next(A)=D\mathrm{next}(A) = D. Below Z on D's list, X prefers D to its partner A, so s(D)=Xs(D) = X and next(D)=A\mathrm{next}(D) = A. The cycle A → D → A is ρ2\rho_2 (A: X→Z, D: Z→X).
  • Likewise s(B)=Ys(B) = Y, next(B)=C\mathrm{next}(B) = C, s(C)=Ws(C) = W, next(C)=B\mathrm{next}(C) = B, and the cycle B → C → B is ρ1\rho_1.

Irving and Leather (1986) showed that

  • there are only O(n2)O(n^2) rotations in total, and every path from the top to the bottom applies each rotation exactly once (which is why opposite edges of the diamond carry the same ρ\rho), and
  • stable matchings correspond one-to-one with the sets of rotations applied (the closed subsets of a partial order on rotations).

This correspondence represents a possibly exponential number of stable matchings with a polynomial-size «graph of rotations». All rotations can be listed in O(n2)O(n^2) time (Gusfield, 1987), and the correspondence is a concrete instance of Birkhoff's representation theorem: every finite distributive lattice is the lattice of closed subsets of some partially ordered set.

With this representation one can also look for stable matchings other than the two extremes — though how hard that is depends heavily on the goal.

  • Egalitarian: minimize the total rank over everyone. Polynomial time (Irving, Leather, Gusfield, 1987).
  • Minimum regret: minimize the worst rank anybody gets. O(n2)O(n^2) (Gusfield, 1987).
  • Sex-equal: minimize the difference between the two sides' rank sums. NP-hard (Kato, 1993).

The demo's panel shows which criteria the selected stable matching is best for. In the running example, the minimum total rank (15) is attained by AZ BW CY DX and the bottom AZ BY CW DX, while the smallest difference between the sides' rank sums (2) is attained by the top AX BW CY DZ and by AX BY CW DZ. All four tie on minimum regret (the worst rank anybody gets is 3), so that badge appears whichever node you select. Which matching to choose depends on «good for whom».

Section 1.4 showed that minimizing total rank does not guarantee stability, but total rank can still be minimized with stability as a constraint. The convex hull of the stable matchings (the stable marriage polytope) is described exactly by polynomially many linear inequalities — the assignment constraints plus one stability inequality per pair (Vande Vate, 1989). Every vertex of this polytope is a stable matching, so «minimize total rank among stable matchings» can also be solved by linear programming.

6. Can lying pay?

6.1 For proposers, honesty is best

Gale–Shapley runs on reported preferences, so the question is whether reporting false preferences can pay. A «report» here may reorder the list, and it may also be truncated: everyone below the cut is declared unacceptable — «I would rather stay unmatched than be matched with them». Stability then also requires that nobody be matched with someone they declared unacceptable (individual rationality, section 8.1).

Theorem (Dubins and Freedman, 1981; Roth, 1982). In proposer-proposing Gale–Shapley, reporting one's true preferences is optimal for every proposer no matter what the others report (a dominant strategy).

Dubins and Freedman also showed that no coalition of proposers, however large, can misreport so that every member strictly gains (their paper is titled «Machiavelli and the Gale–Shapley Algorithm»).

Proof sketch (click to open)

The key is the following «blocking lemma» (credited to J. S. Hwang by Gale and Sotomayor in their 1985 paper «Some remarks on the stable matching problem»).

Let μ\mu be a matching in which nobody is matched with someone they find unacceptable, and let M′M' be the set of proposers who strictly prefer μ\mu to the proposer-optimal stable matching μ0\mu_0. If M′M' is non-empty, there is a blocking pair (m,w)(m, w) of μ\mu in which mm is not in M′M' and ww is the partner in μ\mu of someone in M′M'.

Suppose a coalition CC of proposers lies and every member gains by its true preferences. Let μ\mu be the output under the reported preferences. Agents outside the coalition report truthfully, so none of them is matched with someone unacceptable, and every coalition member does better than at μ0\mu_0, so μ\mu satisfies the lemma's hypothesis under the true preferences. Since C⊆M′C \subseteq M', the lemma gives a blocking pair (m,w)(m, w) of μ\mu. Since mm is outside M′M', it is outside the coalition and reports truthfully; ww is a receiver, so it is truthful too. Then (m,w)(m, w) also blocks μ\mu under the reported preferences. But μ\mu is the Gale–Shapley output for those reports, so it must be stable — a contradiction. With a one-member coalition, this is exactly the proof that a single proposer cannot gain by lying.

6.2 Receivers can gain by truncating

Receivers have no such guarantee. Try the next demo. It starts with a 3-by-3 example with receiver X selected.

Can lying pay? A lab that tries every lie

Pick one agent and edit what they report (click a chip to move it up; set a length to truncate). Everyone else tells the truth. The bottom panel tries every possible report — every order, every truncation.

Instance
Acceptance
Who proposes
Who lies
·
(a receiver)
X's preferences
true
BAC
reported
B
length
Outcome
Truthful: AX BY CZ → A (true #2)
This report: AX BY CZ → A (true #2)
= No change
Valid partners (true order): B, A (2)
As a receiver with two or more valid partners, truncating just below the best one, B (length 1), gets B (section 6.2).
Exhaustive search: all 16 reports X could make
partner obtainednumber of reportsexample report
B (true #1)3B
A (true #2)← truthful7A
C (true #3)5C
unmatched1∅

X can gain by lying: the best reachable partner is B (true #1).

“Unmatched” means the report cut off even partners who were acceptable under the true preferences, leaving nobody to match with.

In this example, when A–C propose, the result is AX BY CZ and X is matched with A, its 2nd choice. But if X shortens its list and reports «only B is acceptable», this happens:

  1. A is rejected by X and proposes to Y; Y lets go of B and trades up to A.
  2. B, now free, proposes to X, and X holds B.

The result is AY BX CZ, and X gets its true first choice, B (in the demo, set the length to 1). The exhaustive table shows that 3 of the 16 reports X could make produce this outcome. Cutting off the bottom of one's list without reordering it is called a truncation strategy. In «Ms. Machiavelli and the Stable Matching Problem» (1985), Gale and Sotomayor showed that if all receivers truncate just below their receiver-optimal partners, even proposer-proposing Gale–Shapley returns the receiver-optimal stable matching.

AY BX CZ, reached through X's lie, is the receiver-optimal stable matching under the true preferences. A receiver's truncation pushes the outcome toward the receivers' end of the lattice; here proposers A and B lose.

Whether a receiver can gain by lying depends only on how many valid partners it has. Combining this truncation argument with the result of Demange, Gale and Sotomayor (1987) — no lie gets you a partner better than your best valid partner under the true preferences — gives: with everyone else truthful, a receiver can gain by lying if and only if it has two or more valid partners. Truncating just below the best valid partner is enough, and nothing does better. The demo's «Outcome» panel lists the selected agent's valid partners and where to cut.

Switch «Who lies» to a proposer (A–C) in the demo: an exhaustive search finds no report that beats the truth (section 6.1).

Truncation is a gamble, though. Switch the demo to «Truncation backfires (3×3)». The only difference from the previous example is Y's preferences (B > A > C), and this market has a single stable matching, AX BY CZ. If X again reports «only B», A is rejected by Y as well and moves to Z, the result is AZ BY, and X, like C, ends up unmatched (set the length to 1 to see it). Truncation pays only if you know everyone else's preferences correctly.

6.3 No stable mechanism makes honesty best for everyone

The receivers' room to manipulate is less a flaw of Gale–Shapley than a property of stability itself.

Theorem (Roth, 1982). There is no mechanism that always returns a stable matching and makes truthful reporting a dominant strategy for all participants.

A 2-by-2 example is enough for the proof. Let A: Y > Z, B: Z > Y, Y: B > A, Z: A > B. There are two stable matchings, AY BZ (best for the left) and AZ BY (best for the right).

  • If the mechanism picks AY BZ, let Y report «only B». Then AY becomes unacceptable to Y, AZ BY is the only stable matching, the mechanism has to pick it, and Y gets its true first choice B.
  • If the mechanism picks AZ BY, let A report «only Y». By the same reasoning AY BZ becomes the only stable matching, and A gains.

Either way, somebody gains by lying. Check it with the demo's «Impossibility (2×2)» preset: it starts with A–B proposing and Y as the liar. After switching to «Y–Z propose», set «Who lies» to A (reporting «only Y» pays). The intuition: when there are several stable matchings, whichever one is chosen, the side that wanted the other end retains an incentive to lie. In real markets, though, this room to lie is usually small (section 7.4).

6.4 Under the Boston mechanism, honest reporting can backfire

Under the immediate acceptance of section 3.3 (the Boston mechanism), honesty is no longer safe, even for proposers. In the running example, B lost its 2nd choice W to A while being rejected by its 1st choice Z. Had B reported W as its first choice, W would have picked B over A in round 1. So under the Boston mechanism, truthfully listing a popular first choice can hurt you, and participants have to think about strategies such as «put a safe option first». Choose «Running example (4×4)» in the demo of section 6.2: it selects B under immediate acceptance, and a report with W first improves B from its true 4th choice to its 2nd. Switch the acceptance rule to DA and no report beats the truth for the same B.

Abdulkadiroğlu and Sönmez (2003) pointed out this problem and proposed deferred acceptance for school choice. Boston decided in 2005 to switch to deferred acceptance.

Japan's JRMP likewise tells participants to «enter every program you wish to train at, in the order you prefer them» and that «changing your first choice because a program is popular does not raise your chances of being matched». The same notes describe the matching as «checking first whether you can match with your first-choice program» — that is, applicants are the proposing side. The advice is the theorem of section 6.1 translated into operating instructions.

7. What happens in a random market

With uniformly random preferences, Gale–Shapley follows simple asymptotic laws. Check them in the next demo (for «100 trials» or «n ≤ 200», press «Run simulation»).

How much does proposing pay in a random market?

Preferences are drawn uniformly at random. Gale–Shapley is run twice — left side (n agents) proposing and right side proposing — and we plot the average rank the left side gets (1 is best). Then add a single agent to the right side and watch.

Right side
Scale
051015201020305075100n (left side size)ln nn / ln n
left side's average rank when the left proposesleft side's average rank when the right proposes
n = 100 (right side 100), mean of 30 runs
left avg rankright avg rank
left proposes4.8720.42
right proposes21.134.75
For reference: ln n = 4.61, n / ln n = 21.71
Proposals when the left proposes: 487.5 (upper bound on the expected value: n·H_n = 518.7)
Share of left agents whose partner differs between the two extreme stable matchings (= the share of left agents who could gain by lying when the right side proposes): 78%

7.1 About nln⁡nn \ln n proposals

With random preferences, the expected number of proposals is at most nHnn H_n, where Hn=1+1/2+⋯+1/n≈ln⁡nH_n = 1 + 1/2 + \cdots + 1/n \approx \ln n (Wilson, 1972). That is far fewer than the worst case n2−n+1n^2 - n + 1: about 500 for n=100n = 100. Since the number of proposals equals the sum of the proposers' final ranks, this also means the proposers' average rank is at most about Hn≈ln⁡nH_n \approx \ln n.

Why nHnn H_n? As section 4.2 showed, the run ends the moment the last receiver gets its first proposal. If proposers «forgot» who had rejected them and each time proposed to a uniformly random receiver, this would be exactly the coupon collector's problem — keep collecting random coupons until you have all nn kinds — whose expected number of draws is exactly nHnn H_n. Real proposers never propose to the same receiver twice, so they need no more proposals than that.

7.2 Average ranks: about ln⁡n\ln n for proposers, n/ln⁡nn / \ln n for receivers

Pittel (1989) showed that in the proposer-optimal stable matching, the proposers' average rank is about ln⁡n\ln n and the receivers' about n/ln⁡nn / \ln n. In the demo's «balanced (n vs n)» setting with n=100n = 100, the left side's average rank is about 5 when the left proposes and about 21 when the right proposes (for reference, ln⁡100≈4.6\ln 100 \approx 4.6 and 100/ln⁡100≈21.7100 / \ln 100 \approx 21.7). The wide gap between the two lines quantifies section 5.3's «proposing is an advantage». The line below the table shows that nearly 80% of the left side have different partners in the two extreme stable matchings: depending on which stable matching is chosen, most people's partners change. By section 6.2, this is also «the share of left agents who could gain by lying when the right side proposes».

7.3 One extra agent outweighs who proposes

Now switch to «right side +1». The two lines nearly coincide: even when the right side proposes, the left side's average rank stays around 5. The share of left agents with different partners drops to about 10%.

Ashlagi, Kanoria and Leshno (2017) showed that in a market that is even slightly unbalanced, in every stable matching the short side (here the left) gets an average rank of about ln⁡n\ln n and the long side about n/ln⁡nn / \ln n, and the set of stable matchings effectively collapses to one. Which side is larger matters far more than which side proposes. Switch to «right side −1» and the left side does poorly whichever side proposes. The number of proposals also jumps when the (now longer) left side proposes.

This agrees with what was observed in practice. When the NRMP switched from hospital-proposing to applicant-proposing, the analysis of Roth and Peranson (1999) found that the effect on actual outcomes was very small. In a market filling about 20,000 positions a year, both the set of stable matchings and the room for strategic manipulation turned out to be «surprisingly small», and they point to a key reason: each applicant interviews for only a small fraction of the available positions (so rank-order lists are short). Real markets are not balanced, rank-order lists are short, and preferences are correlated, so the «width» of the set of stable matchings is narrow to begin with.

7.4 Short lists and unbalanced markets leave little room to manipulate

Receivers do have room to lie, as section 6 showed, but one reason Gale–Shapley remains in use regardless is that in many real markets there is almost no room to manipulate. Immorlica and Mahdian (2005) showed that when the proposers' lists are short (a constant number of randomly chosen entries), even with arbitrary preferences on the receiving side, the fraction of receivers who can gain by lying tends to 0 as n→∞n \to \infty. Kojima and Pathak (2009) extended this to many-to-one markets such as hospitals and residents.

The underlying reason is the fact from section 6.2 for one-to-one markets: only agents with two or more valid partners can gain by lying. In markets with short lists — or, as section 7.3 showed, in markets that are even slightly unbalanced — most agents have at most one valid partner. In the balanced market of section 7.2, where everyone ranks everyone, most agents have several valid partners, so size alone does not remove the room to manipulate.

8. The many-to-one extension and real institutions

8.1 Capacities

The title of Gale and Shapley's paper is «College Admissions and the Stability of Marriage»: its main subject was really college admissions. College hh has a quota qhq_h; each student attends one college, and a college admits at most qhq_h students. More generally,

  • lists may be incomplete: leaving someone off one's list means «I would rather stay unmatched than be matched with them» (unacceptable);
  • the numbers of agents and seats need not match.

Stability is then defined by two conditions.

  1. Nobody is matched with someone they find unacceptable (individual rationality).
  2. There is no student ss and college hh such that ss prefers hh to its current assignment and hh either «has an empty seat and finds ss acceptable» or «prefers ss to one of its current students».

The algorithm hardly changes. Each college keeps the best applications it has received on a «waiting list», up to its quota, and rejects the rest. One can also reduce the problem to the one-to-one case by splitting college hh into qhq_h single «seats».

8.2 Running a residency match

The next demo has residents A–F and hospitals X, Y, Z with two positions each. Lists are incomplete on both sides. Z plays the rural hospital: of the residents who list it (A, C, E), only C is on Z's own rank list.

Residency matching (many-to-one) — deferred acceptance with capacities

This is the round-by-round form of the original 1962 paper. In each round every free applicant applies to their next choice, and each hospital keeps the best applicants among those it held and the new ones, up to capacity.

Residents' rank lists
A
ZYX
B
XY
C
ZY
D
YX
E
YZX
F
YX
Hospitals' waiting lists
X
capacity 2 · seat free
rank list:CFAEBD
Y
capacity 2 · seat free
rank list:BACFE(D not ranked)
Z
capacity 2 · seat free
rank list:FDCB(A, E not ranked)
This round

Residents A–F apply to hospitals X, Y and Z (two positions each) in order of preference. Each hospital keeps a waiting list up to its capacity and turns away anyone not on its rank list.

1 / 5

The four rounds go as follows.

  • In round 1, A applies to Z and D applies to Y, but neither appears on that hospital's rank list, so both are turned away at once.
  • In round 2, A applies to Y, and Y bumps E, whom it had been holding, to take A.
  • In round 3, the bumped E applies to its second choice Z and is turned away at once: E is not on Z's rank list.
  • In round 4, E applies to X, and X bumps D. D has exhausted its list and ends up unmatched.

The result is AY BX CZ EX FY, with D unmatched.

8.3 The rural hospitals theorem

The demo's final panel also shows, in the «Hospitals propose (hospital-optimal)» row, the result when hospitals propose: AY BY CZ EX FX, in which B and F trade places. Yet D is unmatched in both, and the under-filled Z gets only C in both. The next theorem shows that this always holds.

Rural Hospitals Theorem (Roth, 1986). Across all stable matchings,

  • the set of residents who are matched is the same,
  • each hospital fills the same number of positions, and
  • a hospital that does not fill its quota receives exactly the same set of residents.

The name comes from a US policy question: can residents be steered toward rural hospitals that struggle to fill positions, while keeping the match stable? The answer is no. Whichever stable matching is chosen, an under-filled hospital receives the same residents.

Proof: «the same agents are matched» and under-filled hospitals (click to open)

Compare the proposer-optimal μ0\mu_0 with any stable matching μ\mu (reading «unmatched» as worse than any acceptable partner, the proofs of sections 5.2 and 5.3 go through unchanged for incomplete lists). A proposer matched in μ\mu has a partner at least as good in μ0\mu_0 (section 5.2). A receiver matched in μ0\mu_0 has a partner at least as good in μ\mu (section 5.3). Writing P(⋅)P(\cdot) and R(⋅)R(\cdot) for the sets of matched proposers and receivers, and using that both sides always have the same number of matched agents,

∣P(μ)∣≤∣P(μ0)∣=∣R(μ0)∣≤∣R(μ)∣=∣P(μ)∣,\begin{aligned} |P(\mu)| &\le |P(\mu_0)| = |R(\mu_0)| \\ &\le |R(\mu)| = |P(\mu)|, \end{aligned}

so both inclusions, P(μ)⊆P(μ0)P(\mu) \subseteq P(\mu_0) and R(μ0)⊆R(μ)R(\mu_0) \subseteq R(\mu), are equalities. ■\blacksquare

The first two claims extend to many-to-one markets by splitting each hospital into seats. The third claim — that an under-filled hospital receives the same set of residents — is the heart of Roth (1986), and it too has a short proof. Take an under-filled hospital hh and any stable matching μ\mu, and suppose a resident ss assigned to hh in the resident-optimal μ0\mu_0 (after splitting into seats, section 5.2 applies as is) is not at hh in μ\mu. Since μ0\mu_0 is the best stable matching for residents, ss prefers hh to μ(s)\mu(s). By the second claim hh also has a free seat in μ\mu, so (s,h)(s, h) blocks μ\mu — a contradiction. Hence μ0(h)⊆μ(h)\mu_0(h) \subseteq \mu(h), and since both sets have the same size, they are equal. ■\blacksquare

8.4 Hospitals' manipulation, and explaining outcomes with cutoffs

Many-to-one also introduces an asymmetry in strategy-proofness, the property that truthful reporting is optimal. When residents propose, honesty is still optimal for residents; but Roth (1985) showed that in many-to-one problems no stable mechanism makes honesty optimal for hospitals. Even when hospitals propose, a hospital may gain by manipulating its rank list.

A stable many-to-one matching can be explained by «cutoffs». For each hospital that is full, take as its cutoff the lowest-ranked resident it admitted (a hospital with a free seat has none). Then every resident is assigned to their favorite among the hospitals where they rank at or above the cutoff (or that have a free seat and find them acceptable) — otherwise there would be a blocking pair. «You did not get into X because X's last admitted resident ranks above you on X's list» — being able to explain outcomes this way matters for the transparency of an institution. Azevedo and Leshno (2016) developed this view into a supply-and-demand framework. The demo also shows each hospital's cutoff at every round. While a seat is free there is no cutoff; once a hospital is full, its cutoff rises only when more acceptable applications arrive than it has seats — excess demand — much as a price rises under excess demand.

The demo's final panel lists each hospital's cutoff and «why each resident missed the hospitals they prefer». D, for instance, is not on the list of its first choice Y, and at its second choice X it ranks 6th, below the cutoff B (5th), so it gets nothing. E ranks 5th at its first choice Y, below the cutoff F (4th), is not on the list of its second choice Z, and so lands at its third choice X.

8.5 Real institutions

theorypractice
  1. 1952
    The US national residency match (today's NRMP) starts, built on the Boston Pool plan (unrelated to the «Boston mechanism» of school choice) — later shown to produce the same outcome as hospital-proposing deferred acceptance
  2. 1962
    Gale and Shapley, “College Admissions and the Stability of Marriage”: stable matchings always exist, and deferred acceptance finds the proposer-optimal one
  3. 1971
    McVitie and Wilson give an algorithm that lists every stable matching
  4. 1976
    Knuth's “Mariages stables”: the stable matchings form a lattice (credited to Conway), repairing blocking pairs can cycle, and more
  5. 1981–82
    Dubins–Freedman and Roth: truth-telling is dominant for proposers, yet no stable mechanism is strategy-proof for everyone (Roth)
  6. 1984
    Roth shows that the NRMP procedure in use since 1952 yields stable matchings, and argues that this is why the market stopped unraveling
  7. 1985–87
    Irving's stable roommates algorithm; Irving–Leather–Gusfield's polynomial-time algorithm for the egalitarian stable matching
  8. 1998
    The NRMP switches to the applicant-proposing Roth–Peranson algorithm, designed to handle real-world complications such as couples
  9. 2003–05
    New York City high schools adopt deferred acceptance and Boston decides to follow in 2005 (in use from 2006); Japan's residency match (JRMP) starts with the new postgraduate training system of 2004
  10. 2012
    Shapley and Roth receive the Nobel Memorial Prize in Economic Sciences «for the theory of stable allocations and the practice of market design»; Gale had died in 2008
  11. 2015
    Kamada and Kojima show that running deferred acceptance with hospital capacities cut in advance to respect regional caps (as in the JRMP) can produce inefficient and unstable outcomes, and propose flexible deferred acceptance
  12. 2018
    France's Parcoursup runs a form of deferred acceptance «executed by people» for university admissions
  • NRMP (the US residency match): started in 1952. In 1998 it switched to the applicant-proposing Roth–Peranson algorithm, which was designed to handle real-world complications such as «couples» — pairs of applicants (often spouses) who want positions in the same area. With couples a stable matching may not exist and deciding whether one does is NP-complete (Ronn, 1990), but in large markets with a small fraction of couples a stable matching exists with high probability (Kojima, Pathak and Roth, 2013).
  • JRMP (Japan's residency match): introduced together with the new postgraduate clinical training system that began in 2004. The council lists among its features that «the matching algorithm is theoretically established and is made public» and that «no pairing arises that is not on the rank lists». Today the number of positions in each prefecture is also capped, to keep residents from concentrating in big cities. Yuichiro Kamada and Fuhito Kojima (2015) showed that running deferred acceptance after cutting each hospital's capacity in advance to respect such «regional caps» can produce inefficient and unstable outcomes, and proposed «flexible deferred acceptance», which shifts capacity flexibly within each cap.
  • School choice: New York City high schools (from 2003) and Boston public schools (decided in 2005 to move away from the Boston mechanism). Schools have «priorities» (catchment area, siblings and so on) rather than preferences, and students with equal priority have to be ordered by lottery.
  • Parcoursup (French university admissions): since 2018 it has run a form of deferred acceptance «executed by people». Students keep one of the offers they have received and trade up when a better one arrives.
  • Systems design: Maggs and Sitaraman (2015) of Akamai describe formulating global load balancing — assigning groups of clients to server clusters — as a stable matching with capacities.

The 2012 Nobel Memorial Prize in Economic Sciences went to Shapley and Roth «for the theory of stable allocations and the practice of market design». Gale had died in 2008 and so was not among the laureates.

8.6 What stability costs: efficiency

In the marriage model with strict preferences, where both sides' preferences count, every stable matching is Pareto efficient: if some reassignment gave someone a partner they like better while hurting nobody, those two would form a blocking pair of the original matching. The problem arises when one side's «preferences» do not count as welfare.

In school choice, a school's «priorities» are not the school's own preferences but rules such as catchment areas or siblings. That raises a question: if some reassignment makes some students better off and no student worse off, shouldn't it take precedence? Consider the following example. Schools a, b and c each have one seat.

Order (best first)
Student 1's preferencesb > a > c
Student 2's preferencesa > b > c
Student 3's preferencesa > c > b
School a's priorities1 > 3 > 2
School b's priorities2 > 1 > 3
School c's priorities1 > 2 > 3

Student-proposing deferred acceptance gives «1a 2b 3c», so students 1 and 2 both get their second choice. If 1 and 2 swapped schools (1b 2a 3c), both would get their first choice and 3 would lose nothing. After the swap, however, 3 wants a more than c, and a ranks 3 above 2, so (3,a)(3, a) is a blocking pair (in school-choice language, «justified envy»). As long as stability is required, this improvement that hurts nobody cannot be made.

This does not contradict Roth (1982) in section 5.2: student 3 does not strictly gain. The proposer-optimal stable matching rules out improvements that make every proposer strictly better off, not improvements that help some and hurt nobody.

Stability versus efficiency — deferred acceptance and TTC

Schools a, b, c (one seat each) and students 1, 2, 3. Switch between the deferred-acceptance outcome, the outcome after 1 and 2 swap, and top trading cycles (TTC), and check each for justified envy (blocking pairs) and for an improvement that hurts nobody.

Assignment
Preferences and priorities
student 1 prefersb > a > c
student 2 prefersa > b > c
student 3 prefersa > c > b
school a prioritizes1 > 3 > 2
school b prioritizes2 > 1 > 3
school c prioritizes1 > 2 > 3
123abc
Deferred acceptance (DA)
Assignment: 1a 2b 3c (1: choice #2, 2: choice #2, 3: choice #2)
✓ No justified envy (no blocking pair) — stable
✗ An improvement that hurts nobody exists: 1b 2a 3c

Switch to «DA, then 1 and 2 swap» and (3,a)(3, a) appears as a red dashed line (justified envy).

Abdulkadiroğlu and Sönmez (2003) also proposed another mechanism for school choice, «top trading cycles» (TTC) — David Gale's procedure, as reported by Shapley and Scarf (1974), carried over to school choice. Each student points to her favorite school with a free seat, each school points to its highest-priority remaining student, and seats are traded around the resulting cycles. It keeps strategy-proofness for students but trades stability for (student-side) Pareto efficiency; in this example it picks 1b 2a 3c. Step through the rounds in the demo's «TTC» view to watch seats trade around the cycle 1 → b → 2 → a → 1.

Kesten (2010) proposed efficiency-adjusted deferred acceptance (EADA). Starting from the DA outcome, it asks each student whose priority at some school does not help her own assignment — it only pushes others out — to consent to waiving it, and uses those waivers to improve other students' assignments. Consenting does not change the consenter's own assignment, and with full consent the outcome is Pareto efficient (at the cost of strategy-proofness for students). Which of stability, efficiency and strategy-proofness to put first is a value judgment each institution has to make.

9. Generalizations and hardness

Small changes to the basic problem can remove the guarantee that a stable matching exists, or make the problem computationally hard.

VariantExistence and complexity
One-to-one, complete listsAlways exists. O(n2)O(n^2) (Gale–Shapley)
Incomplete lists, unequal sidesAlways exists (some agents may stay unmatched). Linear in input size; the set of matched agents is the same in every stable matching
Many-to-one (with quotas)Always exists. Linear in input size; the rural hospitals theorem holds
Ties (weak stability)Always exists (break ties arbitrarily). With complete lists everyone is matched; but with both ties and incomplete lists, finding a maximum-size weakly stable matching is NP-hard (Iwama, Manlove, Miyazaki, Morita, 1999; Manlove et al., 2002)
Ties (strong stability, super-stability)Need not exist. Existence and construction in polynomial time (Irving, 1994)
Stable roommates (pairs within a single group)Need not exist. Existence and construction in O(n2)O(n^2) (Irving, 1985)
Residency match with couplesNeed not exist. Existence is NP-complete (Ronn, 1990)
Three-sided (3D) matching (each agent ranks pairs from the other two sets)Need not exist. Existence is NP-complete (Ng and Hirschberg, 1991)
Counting stable matchings#P-complete (Irving and Leather, 1986)

With ties, the three notions of stability differ in which pairs count as blocking. A matching is weakly stable if no pair strictly prefers each other, strongly stable if there is not even a pair where one strictly prefers and the other weakly prefers, and super-stable if there is not even a pair who both weakly prefer each other. The stricter the notion, the less existence is guaranteed.

An instance of the roommates problem with no stable matching appears in the original paper. Four people {a,b,c,d}\{a, b, c, d\}: aa ranks b>c>db > c > d, bb ranks c>a>dc > a > d, cc ranks a>b>da > b > d, so all three rank dd last. Whoever is paired with dd is the first choice of someone who is not paired with their own first choice, and those two block (for example, with aa–dd and bb–cc, cc prefers aa to bb and aa prefers cc to dd). Having two sides is the structure that guarantees a stable matching exists.

Existence can still be decided — and a stable matching found — quickly. Irving's (1985) algorithm has two phases. In phase 1 everyone both proposes and receives, deferred-acceptance style; whoever holds a proposal deletes everyone it likes less from its list (and itself from theirs). If someone's list becomes empty, there is no stable matching. In phase 2 it repeatedly finds a rotation in the shortened lists — a cycle in which each person shifts one place, much as in section 5.5 — and eliminates it, until every list has a single entry (a stable matching) or some list becomes empty (none exists). The whole run takes O(n2)O(n^2) time.

The same language of «structure» explains why couples break existence. The key to the many-to-one theory is that hospitals' preferences are «substitutable»: a hospital that wants a resident still wants her when some of the other candidates become unavailable. Under this condition deferred acceptance generalizes all the way to «matching with contracts», which can include terms such as wages, and existence and the lattice structure survive (Kelso and Crawford, 1982; Hatfield and Milgrom, 2005). A couple, however, brings a «complementary» preference onto the applicant side — two positions are worth something only together. The theory assumes that every agent who takes more than one position has substitutable preferences, so couples break that assumption, and with it the guarantee of existence.

Ties matter in practice. School priorities contain huge numbers of ties, and how ties are broken (one lottery for all schools or a separate lottery per school) affects efficiency and fairness. Simulations with New York City data, and the theory, favor a single common lottery (single tie-breaking) (Abdulkadiroğlu, Pathak and Roth, 2009). «Stable improvement cycles» have been proposed to win back, without giving up stability, the efficiency lost by breaking ties with a lottery (Erdil and Ergin, 2008) — but, as Abdulkadiroğlu and colleagues showed in 2009, that improvement cannot be made without harming students' incentives to report truthfully. Work by Japanese researchers in this area includes the studies by Kazuo Iwama, Shuichi Miyazaki and colleagues on the complexity and approximability of stable marriage with ties and incomplete lists (SMTI), and Kato's (1993) proof that sex-equal stable matching is NP-hard.

10. Implementing it

10.1 A Python implementation

Here is proposer-proposing Gale–Shapley, including support for incomplete lists.

from collections import deque
 
 
def gale_shapley(proposer_prefs, receiver_prefs):
    """Deferred acceptance with the proposers proposing.
 
    proposer_prefs[p]: receivers acceptable to p, best first
    receiver_prefs[r]: proposers acceptable to r, best first
    Returns match[p] = p's partner (or None).
    """
    n_p, n_r = len(proposer_prefs), len(receiver_prefs)
    # rank[r][p]: position of p in r's list (smaller is better); None if unacceptable
    rank = [[None] * n_p for _ in range(n_r)]
    for r, prefs in enumerate(receiver_prefs):
        for k, p in enumerate(prefs):
            rank[r][p] = k
 
    next_choice = [0] * n_p   # index of the next receiver p will propose to
    holding = [None] * n_r    # proposer that r is holding «tentatively»
    free = deque(range(n_p))  # proposers without a partner
 
    while free:
        p = free.popleft()
        if next_choice[p] == len(proposer_prefs[p]):
            continue  # list exhausted: p stays unmatched
        r = proposer_prefs[p][next_choice[p]]
        next_choice[p] += 1
        if rank[r][p] is None:
            free.append(p)  # r does not accept p
        elif holding[r] is None:
            holding[r] = p  # r is free: hold p tentatively
        elif rank[r][p] < rank[r][holding[r]]:
            free.append(holding[r])  # trade up: the old partner becomes free
            holding[r] = p
        else:
            free.append(p)  # r prefers its current partner: reject
 
    match = [None] * n_p
    for r, p in enumerate(holding):
        if p is not None:
            match[p] = r
    return match
 
 
# A..D = 0..3, W..Z = 0..3 (the running example)
P = [[0, 1, 3, 2], [3, 0, 2, 1], [3, 2, 0, 1], [3, 1, 2, 0]]
R = [[2, 1, 3, 0], [3, 1, 0, 2], [1, 2, 3, 0], [0, 3, 2, 1]]
print(gale_shapley(P, R))  # [1, 0, 2, 3] → AX BW CY DZ
print(gale_shapley(R, P))  # [2, 3, 1, 0] → WC XD YB ZA

Each iteration is O(1)O(1) and the number of proposals never exceeds the total length of the proposers' lists. Because the rank table is a full np×nrn_p \times n_r grid, though, the running time is linear in the input size only for complete lists. For short lists, keep each receiver's ranks in a dictionary, as blocking_pairs does in section 10.2, and the time is proportional to the total length of the lists.

10.2 How to test it

Matching algorithms are a natural fit for tests against a brute-force oracle. For n≤6n \le 6 or so, all n!n! matchings can be examined, so with random inputs we can check, many times over, that

  1. the output has no blocking pair (stability), and
  2. the output is proposer-optimal among all stable matchings found by brute force.
import itertools
import random
 
 
def blocking_pairs(proposer_prefs, receiver_prefs, match):
    """Blocking pairs of match[p] = r (or None)."""
    partner_of = {r: p for p, r in enumerate(match) if r is not None}
    rank_r = [{p: k for k, p in enumerate(prefs)} for prefs in receiver_prefs]
    pairs = []
    for p, prefs in enumerate(proposer_prefs):
        for r in prefs:  # from p's favorite downwards
            if match[p] == r:
                break  # anything below the current partner cannot block
            if p not in rank_r[r]:
                continue  # r does not accept p
            q = partner_of.get(r)
            if q is None or rank_r[r][p] < rank_r[r][q]:
                pairs.append((p, r))
    return pairs
 
 
def stable_matchings(proposer_prefs, receiver_prefs):
    n = len(proposer_prefs)
    for perm in itertools.permutations(range(n)):
        if not blocking_pairs(proposer_prefs, receiver_prefs, list(perm)):
            yield list(perm)
 
 
def check(trials=300, n=5, seed=0):
    rng = random.Random(seed)
    for _ in range(trials):
        P = [rng.sample(range(n), n) for _ in range(n)]
        R = [rng.sample(range(n), n) for _ in range(n)]
        gs = gale_shapley(P, R)
        assert not blocking_pairs(P, R, gs)  # stable
        for m in stable_matchings(P, R):  # proposer-optimal
            assert all(P[p].index(gs[p]) <= P[p].index(m[p]) for p in range(n))
 
 
check()  # silence means every check passed

The TypeScript implementation behind the demos on this page (src/lib/stable-matching.ts) is tested the same way — against brute force or against the two extreme stable matchings — for properties such as «the result and the set of proposals do not depend on the order», «proposer-optimal and receiver-pessimal», «at most n2−n+1n^2 - n + 1 proposals», «no proposer gains from any report», «joins and meets are stable matchings» and «the rural hospitals theorem».

10.3 Practical notes

  • How to break ties is a major design decision. The tie-breaking rule changes both the outcome and its efficiency, and the rule itself becomes a subject of fairness debates.
  • Handle unacceptability explicitly. Never matching someone with a partner absent from their list (individual rationality) is part of stability.
  • The result does not depend on the order of proposals, so implementation details (queue or stack, parallel or not) do not change the output. That is a big advantage for reproducibility, and for processing each round in parallel per receiver.
  • Explainability. The cutoffs of section 8.4 explain to each individual «why this was the result».
  • Choose deliberately which side proposes. The proposing side is favored, and only the proposing side gets the «honesty is best» guarantee — and in many-to-one markets only when the single-seat side (residents, students) proposes (section 8.4). Decide, in light of the institution's goals, whom it should protect.
  • Do not cap the length of rank lists. With a cap, even deferred acceptance stops being strategy-proof: applicants must decide which options to include (Haeringer and Klijn, 2009). For years New York City's high-school match let students rank at most 12 programs (Abdulkadiroğlu, Pathak and Roth, 2005), counting each program within a school separately; the cap has since been lifted.
  • Run it once from each side. If the results coincide, the stable matching is unique, and in a one-to-one market nobody can gain by lying while everyone else is truthful. If they differ, the agents whose partners change are exactly those with two or more valid partners, and those among them on the receiving side have room to truncate (section 6.2).
  • Check the output and make it reproducible. blocking_pairs from section 10.2 runs in time proportional to the total length of the lists, so it can be used as a production assertion for one-to-one output. It assumes that nobody is matched to someone unacceptable, so check that first. For many-to-one output, rewrite it to test whether the institution «has a free seat» or the applicant «ranks above the lowest admitted». If ties are broken by lottery, record the random seed so that a third party can reproduce and verify the result.
Common misconceptions.
  • «It maximizes total happiness» — no; a total-maximizing matching can be unstable (section 1.4).
  • «Processing order or parallelism changes the result» — no (sections 3.4 and 5.2).
  • «The receiving side, which gets to choose, is better off» — the reverse: proposing is the advantage (section 5.3).
  • «Under deferred acceptance nobody has a reason to lie» — only proposers are guaranteed that (sections 6.1–6.2).
  • «Stable means efficient» — with strict preferences and both sides' welfare counted, a stable matching is Pareto efficient; but when only one side's welfare counts, as with students in school choice, an improvement that hurts no student can remain (section 8.6).
  • «Stable means as many pairs as possible» — not with incomplete lists. Two mutually acceptable agents who are both unmatched would form a blocking pair, so a stable matching is maximal (no pair can be added) and therefore has at least half the maximum number of pairs. Moreover, every stable matching has the same number (section 8.3).

Summary

  • Stability means having no blocking pair (two agents who prefer each other to their current partners); it is the condition under which nobody has an incentive to trade outside the system.
  • The naive approach of fixing blocking pairs one at a time can cycle.
  • Gale–Shapley (deferred acceptance) has proposers propose in order of preference while receivers hold the best proposal so far; it always returns a stable matching after at most n2−n+1n^2 - n + 1 proposals.
  • The output does not depend on the order of proposals and is the best stable matching for proposers and the worst for receivers. The stable matchings form a distributive lattice that rotations represent compactly.
  • Truthful reporting is a dominant strategy for proposers (and a coalition cannot make all its members gain). Receivers can gain by truncation, but only when they have two or more valid partners, and no stable mechanism makes honesty best for everyone. In markets with short lists or unequal sides, though, the room to manipulate almost disappears.
  • In random markets proposers get an average rank of about ln⁡n\ln n and receivers about n/ln⁡nn / \ln n — but with just one extra agent on one side, the result is nearly the same whichever side proposes.
  • The many-to-one extension is used in residency matches and school choice, and an under-filled hospital receives the same residents in every stable matching (the rural hospitals theorem). Outcomes can be explained to each individual with «cutoffs».
  • When only one side's welfare counts (students in school choice), stability can conflict with efficiency, and alternatives such as TTC and EADA are also on the table.
  • Generalizations such as ties, couples, roommates and three-sided matching can lose existence or become NP-hard.

References

Further reading. For a general audience, Roth's own Who Gets What — and Why: The New Economics of Matchmaking and Market Design (Houghton Mifflin Harcourt, 2015) is the natural entry point. The standard texts are Roth and Sotomayor (1990) for the theory, Gusfield and Irving (1989) for the structure of stable matchings and its algorithms, and D. F. Manlove's Algorithmics of Matching Under Preferences (World Scientific, 2013) for the variants and their complexity. Among algorithms textbooks, J. Kleinberg and É. Tardos's Algorithm Design (Addison-Wesley, 2005) opens its first chapter with this very problem.