Gale–Shapley (stable matching)
Men propose in order of preference and women always keep the best offer so far; the result is a stable matching: no two people both prefer each other to their partners. At most n² proposals.
There are n men and n women, and each ranks everyone on the other side. A matching is unstable if some man m
and woman w both prefer each other to their current partners (a "blocking pair"). We want a stable matching. The
same problem assigns medical residents to hospitals.
- Time:
O(n²) - Space:
O(n²) - CLRS, section 25.2
Three men and three women. Woman 0 drops man 0 for man 1, and woman 1 drops man 2 for man 0; the result: (0, 1), (1, 0), (2, 2). Each row of M is one man's list of women, best first, and each row of W one woman's list of men.
def gale_shapley(M, W):# M[m]: man m's list of women, best first; W[w]: woman w's list of men, best first. People are numbered from 0.n = len(M)for prefs in M + W:if sorted(prefs) != list(range(n)):return Nonerank = [[0] * n for _ in range(n)]for w in range(n):for i in range(n):rank[w][W[w][i]] = iwife = ["·"] * nhusband = ["·"] * nnxt = [0] * n # the next woman on each man's listfree = list(range(n))rejections = 0while free:m = free[0]w = M[m][nxt[m]]nxt[m] = nxt[m] + 1if husband[w] == "·":husband[w] = mwife[m] = wfree.pop(0)elif rank[w][m] < rank[w][husband[w]]:old = husband[w]husband[w] = mwife[m] = wwife[old] = "·"free.pop(0)free.append(old)else:rejections = rejections + 1return wife
Start
Local variables
Orange = changed in this step
M list
W list
Call stack
- gale_shapley()line 1
Explanation
The problem
There are n men and n women, and each ranks everyone on the other side. A matching is unstable if some man m
and woman w both prefer each other to their current partners (a "blocking pair"). We want a stable matching. The
same problem assigns medical residents to hospitals.
The algorithm (Gale and Shapley, 1962)
While some man is free, he proposes to the best woman he has not yet proposed to. If she is free she accepts; if she is engaged she keeps the better of the two, and the other becomes free.
Why it works
- It ends: each man proposes to each woman at most once: at most
n²steps. - Everyone is matched: a woman who has had a proposal is never free again; if a man had tried everyone and stayed free, every woman would be engaged, which the equal numbers rule out.
- Stability: if
mpreferswto his wife, he proposed towearlier, and she turned him down for someone better.
The result is the best stable matching possible for the proposers.
The input
Row m of M is man m's list of women, best first, and row w of W is woman w's list of men; people are
numbered from 0.