Chapter 1 · Design & Analysis of Algorithms

Stable Matching
& Gale-Shapley

A Nobel Prize-winning algorithm that turns a romantic puzzle into one of computer science's most elegant solutions — and forms the blueprint for everything from medical residency placements to college admissions.

📅 1962 Origin 🏅 Nobel 2012 ⏱ O(n²) Runtime 🎯 Boy-Optimal

01 The Problem Origin

The stable matching problem was introduced in 1962 by mathematicians David Gale and Lloyd Shapley. Their paper, "College Admissions and the Stability of Marriage," asked a deceptively simple question: can you always arrange marriages between men and women such that no two people would prefer each other over their assigned partners?

1962
Gale & Shapley publish the problem
Introduced the stable matching problem and the deferred acceptance algorithm.
1984
National Resident Matching Program
NRMP adopts a variant of Gale-Shapley to assign medical students to residency programs in the US.
2012
Nobel Prize in Economics
Alvin Roth & Lloyd Shapley (Gale had passed away in 2008) received the Nobel Prize for the theory of stable allocations.
Real-world impact
The algorithm is used today for matching medical students to residencies, students to schools (NYC, Boston), kidney donors to recipients, and more.

02 Problem Formulation

Setting
The Stable Marriage Problem

Given n boys and n girls, where each person has a complete, strict preference list over all members of the opposite sex, find a perfect matching (every person is matched) such that the matching is stable.

👥
Equal groups
Exactly n boys and n girls. Everyone must be matched (perfect matching).
📋
Complete lists
Each person ranks all members of the other group. No ties, no omissions.
🔒
Strict preferences
No person is indifferent between any two candidates. All rankings are distinct.

Example: 2 Boys × 2 Girls

Consider Bob, Brad, Alice, and Angelina. Each has a ranked preference list over the opposite sex:

Boy1st Choice2nd Choice
Bob Angelina Alice
Brad Angelina Alice
Girl1st Choice2nd Choice
Alice Brad Bob
Angelina Brad Bob

Both boys prefer Angelina; both girls prefer Brad. There's a clear "conflict" — but as we'll see, a stable matching always exists.

03 Rogue Couples & Stability

Definition
Rogue Couple

A rogue couple (or blocking pair) is a boy b and girl g who are not matched to each other, but who both prefer each other over their current partners.

  • b prefers g over his assigned partner b'
  • g prefers b over her assigned partner g'
Definition
Stable Matching

A perfect matching is stable if it contains no rogue couple. In other words, there is no unmatched pair who both prefer each other over their current partners.

Visual Intuition

❌ Unstable Matching
Adam Ben Amy Beth Rogue pair: Adam+Amy both prefer each other

Adam matched to Beth, Ben to Amy — but Adam prefers Amy and Amy prefers Adam. They'd elope!

✅ Stable Matching
Adam Ben Amy Beth No rogue couple exists — matching is stable ✓

Adam matched to Amy, Ben to Beth. No unmatched pair mutually prefers each other.

Key insight
Stability doesn't mean everyone is happy with their match. It means no two people have both the desire and the ability to ditch their partners for each other. The matching is self-enforcing.

04 Why It's Tricky

Before giving the algorithm, consider why this isn't obvious. You might wonder: does a stable matching always exist? Could preferences create a cycle where no stable assignment is possible?

The Love Triangle: No Stable Matching in the Same-Sex Case

Suppose we have three boys — Alice, Bob, Carol (ignoring gender labels) — where:

Person1st Choice2nd Choice
AliceBobCarol
BobCarolAlice
CarolAliceBob

This forms a cyclic preference. Any pairing leaves someone as a rogue:

Critical point
A stable matching is not guaranteed for arbitrary (non-bipartite) preference structures. The Gale-Shapley algorithm only works — and stability only always exists — for the bipartite case (two distinct groups with opposite-sex preferences).

05 The Gale-Shapley Algorithm

Gale and Shapley described their algorithm colorfully as a "mating ritual" that plays out over several days. The algorithm is sometimes called the Deferred Acceptance Algorithm because girls never immediately commit — they always keep their options open.

Algorithm — The Mating Ritual
Gale-Shapley (Boy-Proposes Version)

Each day proceeds in three phases:

  • Morning — Boys Propose: Each free (unengaged) boy courts the highest-ranking girl on his list whom he hasn't already courted.
  • Afternoon — Girls Deliberate: Each girl who receives proposals keeps (tentatively) her most preferred suitor and rejects all others. A girl who was previously "holding" a boy may now dump him for a better one.
  • Evening — Crossed Off: Each rejected boy crosses the rejecting girl off his list.

The ritual ends when no boy is rejected — all current tentative engagements become marriages.

Deferred acceptance
Girls say "maybe" but never a permanent "yes" until the very end. They can upgrade at any time. Boys, once rejected, move down their list and never go back. This asymmetry is crucial.

Pseudocode

function GaleShapley(boys, girls): // Initialize: everyone free, no proposals made while ∃ free boy b who hasn't proposed to all girls: g ← b's highest-ranked girl not yet courted if g is free: engage(b, g) else if g prefers b over current partner b': disengage(b', g) engage(b, g) else: reject(b, g) // b crosses g off his list return current engagements as final matching

06 Interactive Simulator

Step through the Gale-Shapley algorithm yourself. Watch how proposals, rejections, and upgrades unfold day by day.

🔬 Mating Ritual Simulator Interactive
0
Ready to begin. Press "Next" to start the mating ritual.
Simulator ready. Choose an example and press Next to begin.
✅ Final Stable Matching

07 Proof of Termination

Theorem 1
The algorithm terminates within n² + 1 days.
Proof — Counting Crossings

Define the potential function Φ = total number of (boy, girl) pairs that have not yet been crossed off by that boy. Initially, Φ = n² (each boy has n girls on his list). At the start of each day after day 1, at least one new crossing occurs (since at least one boy was rejected the previous evening). So Φ strictly decreases by at least 1 each day. Since Φ ≥ 0, and it can't go below 0, the process must stop in at most n² steps. Adding the initial day, the algorithm terminates within n² + 1 days.

■ QED
Potential Function Intuition
Initial pairs
(all uncrossed)
≥1
Crossings per
day (day 2+)
≤n²+1
Max days
to finish

08 Four Key Lemmas

These four lemmas are the building blocks for proving correctness and optimality. Each follows directly from how the algorithm works.

Lemma 1
If a boy gets married, he courted every girl he liked better.

Formally: if boy b marries girl g, then b has courted every girl he prefers over g.

Proof

Boy b proposes in order of his preference list. He proposes to g only after being rejected by or rejected from all girls above g on his list. Since b marries g, he never goes below g — meaning he has courted every girl he prefers to g.

■ QED
Lemma 2
If a boy never gets married, he has courted every girl.

Formally: if boy b remains single at the end, then b has courted all n girls.

Proof

By the termination condition, the algorithm stops when no boy is rejected. If b is still free, he must have been rejected by everyone on his list (otherwise the algorithm would have continued with b courting another girl). Therefore b has proposed to all n girls.

■ QED
Lemma 3
A girl always marries her favorite among all her suitors.

Formally: girl g marries the best boy among those who ever courted her, by her preference ordering.

Proof

When girl g receives multiple proposals on any day, she keeps her most preferred suitor and rejects the rest. Crucially, once g holds onto a boy, she only ever upgrades — she replaces him only if someone she prefers comes along. Therefore her final partner is the best boy who ever courted her.

■ QED
Lemma 4
If a girl is ever courted, she gets married.

Formally: if at least one boy courts girl g, then g ends up married.

Proof

Once g receives a proposal, she holds onto someone (by the algorithm's rule). A girl only releases a boy to take a better one — she never becomes free again once she's been courted. Therefore if she's ever courted, she ends up holding someone when the algorithm terminates.

■ QED

09 Proof of Correctness

Theorem 2
Everyone gets married.
Proof

Suppose for contradiction that some boy b does not marry. By Lemma 2, b courted all n girls. By Lemma 4, every girl he courted gets married. So all n girls are married. But there are only n boys (equal groups), and all n girls are married to boys — so all boys must also be married. Contradiction with b being single.

■ QED
Theorem 3
The algorithm produces stable marriages — no rogue couples.
Proof — by Contradiction

Suppose boy b and girl g form a rogue couple: b prefers g over his wife g', and g prefers b over her husband b'.

Since b prefers g over g', by Lemma 1, b must have courted g before g' (he proposes in decreasing preference order).

But g ended up with b', not b. By Lemma 3, g marries her favorite among all who courted her. Since b courted g and g didn't end up with b, she must prefer b' over b.

But this contradicts our assumption that g prefers b over b'. ↯

■ QED
Summary so far
We've proven: (1) the algorithm always terminates in ≤ n²+1 days, (2) it produces a perfect matching where everyone is married, and (3) that matching is stable (no rogue couples). A stable perfect matching always exists for the bipartite case.

10 Who Benefits? Boy-Optimal & Girl-Pessimal

The algorithm doesn't just produce a stable matching — it produces a specific one with a remarkable fairness (or unfairness) property.

Definition
Valid Partner

A girl g is a valid partner for boy b if there exists some stable matching in which they are together. Among all valid partners, b's optimal mate is his most preferred, and his pessimal mate is his least preferred valid partner.

🏆 For Boys
Boy-Optimal
Every boy gets his best possible valid partner — the highest-ranked girl he could be matched with in any stable matching.
😔 For Girls
Girl-Pessimal
Every girl gets her worst possible valid partner — the lowest-ranked boy she could receive across all stable matchings.
Theorem 4
Every boy is matched to his optimal valid partner.
Proof sketch

Suppose for contradiction that some boy b is rejected by his optimal mate g during the algorithm — g drops b for some boy b' she prefers. So g prefers b' over b.

Since g is b's optimal mate, there exists a stable matching S where b is with g. In S, b' is matched to some girl g' (not g).

But b' prefers g over his current partner g' (he wouldn't have proposed to g first if he preferred g' — boys propose in order). And g prefers b' over b. So (b', g) is a rogue couple in S — contradicting S being stable. ↯

■ QED
Theorem 5
Every girl is matched to her pessimal valid partner.
Proof sketch

Let M* be the Gale-Shapley matching. Suppose girl g is matched to b in M*. Suppose there is another stable matching S where g is matched to b', and suppose g prefers b' over b (i.e., b is not pessimal for g).

By Theorem 4, b' gets his optimal mate in M*. Since b' is with g in S, g is a valid partner for b'. So b''s optimal mate is at least as good as g. But in M*, b' ends up with someone at least as preferred as g. In S, g prefers b' over her partner in S only if... This leads to a contradiction with S being stable.

■ QED
The Bias
The proposing side (boys) always gets the best deal. If girls proposed instead, the matching would be girl-optimal and boy-pessimal. This is why real-world implementations matter — in NRMP, hospitals used to propose to students, getting hospital-optimal outcomes. Reforms switched to student-proposing.

11 Uniqueness

An interesting property: the boy-optimal stable matching is unique, as is the girl-optimal stable matching. But these two may differ.

Observation
If boy-optimal = girl-optimal, the matching is the only stable matching.

If running Gale-Shapley with boys proposing gives the same result as girls proposing, then exactly one stable matching exists. Conversely, if they differ, there are at least two distinct stable matchings.

Uniqueness criterion
Run GS with boys proposing → result M₁.
Run GS with girls proposing → result M₂.
If M₁ = M₂: unique stable matching. If M₁ ≠ M₂: multiple stable matchings exist.

12 Number of Stable Matchings

The number of stable matchings can be exponential in the worst case. This means we can't enumerate all of them efficiently.

Fact
Exponentially many stable matchings

For certain preference lists with n boys and n girls, the number of stable matchings can be as large as 2^(n/2).

Consider this construction for n = 4 (2k with k=2): arrange preferences so that stable matchings correspond to binary choices at each of k "decision points." Each decision point independently doubles the count, giving 2k = 2n/2 total stable matchings.

\[\text{Max stable matchings} = 2^{n/2}\]
Implication
Although finding one stable matching is easy (polynomial), enumerating all of them is intractable for large n. This separates the problem from simpler matching problems.

13 Optimization Criteria

Among all stable matchings, which one should we pick? Researchers have proposed several optimality criteria for choosing a "best" stable matching. Their complexity tells an interesting story.

Definitions
Costs of a Stable Matching M

For a stable matching M, define the rank of a pair (b, g) in M as boy b's rank of g on his list. Then:

🎯
Regret Cost r(M)
The maximum rank assigned to anyone in M — how bad is the worst-off person?

r(M) = max rank
⚖️
Egalitarian Cost c(M)
The sum of all ranks — the total "cost" distributed across everyone.

c(M) = Σ ranks
🤝
Sex-Equitable d(M)
The difference between total boy-ranks and total girl-ranks — how fair is it between the two groups?

d(M) = |Σboys - Σgirls|
Criterion Goal Complexity Notes
Min-Regret Minimize worst rank Polynomial Run GS, check and restrict
Min-Egalitarian Minimize total ranks Polynomial Network flow approach
Sex-Equal Equalize boys' & girls' total ranks NP-hard Requires searching exponential space
NP-hardness surprise
Finding the sex-equal stable matching — the fairest one between the two groups — is NP-hard. Despite stable matching itself being easy, this optimization variant is computationally intractable. Fairness is hard!
\[\text{Min-Regret} \in P \quad\text{Min-Egalitarian} \in P \quad\text{Sex-Equal} \in \mathsf{NP}\text{-hard}\]

Chapter Summary

📐
The Problem
n boys + n girls, complete strict preferences. Find a stable perfect matching (no rogue couples).
⚙️
The Algorithm
Gale-Shapley "mating ritual": boys propose down their lists, girls hold best suitor. Terminates in ≤ n²+1 days.
🔬
Correctness
Always terminates. Always produces a perfect matching. Always stable. Proven via 4 lemmas + 3 theorems.
The Bias
Boy-optimal & girl-pessimal. Proposing side always wins. Up to 2^(n/2) stable matchings exist. Sex-equal optimization is NP-hard.