learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Gale-Shapley Algorithm

Nobody would rather swap

Matches the two sides of a bipartite graph by their rankings: free proposers ask down their lists and receivers keep the best offer, until no pair would rather swap

Time: O(n²)
Space: O(n²)
Use Case: Residency matching, school choice, two-sided markets
Showing the example graph for this algorithm.
Rankings, best first
Proposers (the start vertex’s side)
A
B
C
D
Receivers
1
2
3
4

Click a name to rank it one place higher. Choose a start vertex on the other side to let that side propose.

Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Gale-Shapley (Stable Matching)

The stable matching problem pairs the members of two groups, such as students and schools or doctors and hospitals, when everyone ranks the other side. A matching is stable if no student and school would both rather have each other than the partners they got: such a pair would simply break the rules and leave together. David Gale and Lloyd Shapley showed in 1962 that a stable matching always exists and gave an algorithm that finds one, now called deferred acceptance. The problem is also known as the stable marriage problem. Alvin Roth and Lloyd Shapley received the 2012 Nobel Memorial Prize in Economics for the theory and its use in real markets.

How it works

One side proposes and the other receives. Every free proposer asks the receiver it ranks highest among those it has not asked yet. A free receiver accepts, and an engaged receiver compares the new offer with its partner, keeps the one it ranks higher and turns the other away, who becomes free again. Receivers only trade up and proposers only move down their lists, so nobody proposes twice to the same receiver, and the process ends after at most n² proposals. The result is stable, and it is the best stable matching for every proposer and the worst for every receiver, so which side proposes matters. In the visualizer the start vertex's side proposes, and each vertex's ranking is shown next to it.

Applications

Deferred acceptance runs the National Resident Matching Program, which places medical graduates in US hospitals, and assigns students to public schools in New York, Boston and many other cities. Variants allocate university places and assign cadets to army branches. In computer science it is a standard example of an algorithm with a clean invariant and a proof of termination, and it is taught next to bipartite matching, which ignores preferences and only maximises the number of pairs.

Pseudocode

Gale-Shapley keeps a queue of free proposers and two pieces of state: for each proposer the position it has reached in its own list, and for each receiver its current partner. A proposer never asks the same receiver twice.

GaleShapley(proposers P, receivers R, rankings):
    every p and every r is free
    next[p] = 1 for every p        // next position to try
    while some free p has next[p] <= length of its list:
        r = list(p)[next[p]]
        next[p] = next[p] + 1
        if r is free:
            engage(p, r)
        else if r ranks p above its partner q:
            q becomes free
            engage(p, r)
        else:
            r rejects p             // p stays free
    return the engaged pairs

Two monotone quantities drive the proof. A receiver's partner only gets better, and a proposer only moves down its list, so there are at most n² proposals. The result is stable: if p prefers r to its final partner, p proposed to r earlier and was turned down or left for someone r ranks higher, and r's partner has only improved since, so r does not prefer p.

Worked example, step by step

Students A, B, C and D apply to schools 1, 2, 3 and 4, each with one seat, on the example this page loads. The students propose.

Example graph: Students' rankings: A 3, 1, 2, 4. B 1, 2, 4, 3. C 3, 1, 2, 4. D 3, 4, 2, 1. Schools' rankings: 1 D, A, B, C. 2 A, C, D, B. 3 B, D, A, C. 4 C, D, B, A.

  1. First offers. A proposes to 3 and B to 1. Both schools are free and accept.
  2. C is turned down twice. C proposes to 3, which ranks its partner A third and C fourth, so it says no. School 1 also prefers its partner B. C's third choice, school 2, is free and accepts.
  3. A trade up. D proposes to 3, which ranks D second and A third, so it leaves A for D. A is free again.
  4. A chain reaction. A moves on to its second choice, 1, which ranks A second and B third. School 1 trades B for A, and B is free.
  5. The last proposals. B proposes to 2, which keeps C (its second) over B (its fourth). B's next choice, 4, is free and accepts. Nobody is free any more.

After 9 proposals the matching is A-1, B-4, C-2, D-3, and no student and school prefer each other to their partners. If the schools proposed instead, the result would be A-2, B-3, C-4, D-1: every student would get a worse school and every school a better student, which shows how much the choice of the proposing side matters.

Complexity, and where it comes from

Time: O(n²) · Space: O(n²)

Each proposer asks each receiver at most once, so there are at most n² proposals for n people on each side, and the worst case comes close, with n(n - 1) + 1 proposals. Each proposal costs O(1) if every receiver's ranking is first turned into an array giving the position of each proposer, which takes O(n²) time and space for all receivers. Reading the rankings already takes O(n²), so the algorithm is linear in the size of its input.

When to use Gale-Shapley (Stable Matching), and when not to

Stable matching is one of several ways to pair two groups. Which one fits depends on whether the pairs have preferences, costs or only a yes or no.

AlternativePrefer it whenCost
Hopcroft-KarpPairs are simply allowed or not and the goal is as many pairs as possible. Preferences play no role.O(E√V)
Hungarian methodEvery pair has a cost or a score and the total must be optimal, as when assigning workers to jobs.O(n³)
Receiver-proposing Gale-ShapleyThe other side's interests come first: the same algorithm with the roles swapped gives the stable matching that is best for the receivers.O(n²)
Irving's stable roommates algorithmThere is a single group and anyone can be paired with anyone. A stable matching may then not exist, and the algorithm finds one or proves there is none.O(n²)
Top trading cyclesOne side owns objects instead of having preferences, as in house allocation or kidney exchange. It is strategy-proof and Pareto efficient.O(n²)

Common pitfalls

  • Expecting a fair result. The algorithm favours the proposing side: each proposer gets its best stable partner and each receiver its worst. Choosing which side proposes is a policy decision, and the US residency match switched to applicants proposing in 1998 for that reason.
  • Confusing stable with maximum. A stable matching need not have the most pairs or the best total score. It only guarantees that no pair has a reason to break away. When some pairs are not allowed, every stable matching leaves the same people unmatched, by the rural hospitals theorem.
  • Comparing ranks by scanning lists. Finding where a proposer stands in a receiver's list by searching it makes each proposal O(n) and the algorithm O(n³). Building the array of positions first keeps every comparison O(1).
  • Assuming nobody can game it. Proposers can never gain by misreporting their rankings, but receivers sometimes can, for example by turning down an offer they would accept. No stable matching mechanism is strategy-proof for both sides.

Frequently asked questions

What is the Gale-Shapley algorithm?
An algorithm that pairs the members of two groups who rank each other, so that no two people prefer each other to the partners they get. Free members of one side propose down their lists, and the other side keeps the best offer so far. David Gale and Lloyd Shapley published it in 1962.
What is a stable matching?
A matching with no blocking pair: no proposer and receiver who both prefer each other to their current partners, being unmatched counting as worst. Gale and Shapley proved that every instance of the stable marriage problem has at least one stable matching.
Is the Gale-Shapley result unique?
Not always, because there can be many stable matchings. Every run with the same proposing side ends with the same one, whatever order the free proposers take turns in, and it is the best stable matching for that side. Swapping the sides gives the other extreme, and when the two coincide the stable matching is unique.
Where is the Gale-Shapley algorithm used?
In the National Resident Matching Program for US doctors, in school choice in New York and Boston, in university admissions in several countries and in assigning cadets to army branches. Alvin Roth and Lloyd Shapley received the 2012 Nobel Memorial Prize in Economics for this work.
What is the time complexity of Gale-Shapley?
O(n²) for n people on each side, because each proposer asks each receiver at most once and every proposal takes constant time once each receiver's ranking is stored as an array of positions. That is linear in the size of the input, the n² ranks.

Related algorithms: Hopcroft-Karp Matching, Bipartite Check, Maximum Flow, Min-Cost Max Flow

An example graph: you can change it, or start blank.

Zoom Controls

46%
Nodes: 8
Edges: 16