Stable Matching (Gale-Shapley) - Problem

The Stable Matching Problem is a classic problem in computer science and economics. Given two groups of equal size (traditionally called proposers and reviewers), where each member has a preference ranking of all members in the other group, find a matching where no two people would prefer each other over their current partners.

Implement the Gale-Shapley algorithm to find a stable matching. The algorithm guarantees that:

  • Every person gets matched
  • No blocking pairs exist (unstable matches)
  • The matching favors the proposing group

Input format:

  • proposerPrefs: 2D array where proposerPrefs[i] is proposer i's preference list (most preferred first)
  • reviewerPrefs: 2D array where reviewerPrefs[i] is reviewer i's preference list (most preferred first)

Return a matching array where result[i] is the reviewer assigned to proposer i.

Input & Output

Example 1 — Basic 3x3 Case
$ Input: proposerPrefs = [[1,2,0]], reviewerPrefs = [[2,1,0]]
Output: [1]
💡 Note: With 1 proposer and 1 reviewer, proposer 0 gets their first choice, reviewer 1. Since there's only one pair, this is automatically stable.
Example 2 — Simple Competition
$ Input: proposerPrefs = [[1,0],[1,0]], reviewerPrefs = [[0,1],[0,1]]
Output: [1,0]
💡 Note: Both proposers prefer reviewer 1, but reviewer 1 prefers proposer 0. Proposer 0 gets reviewer 1, proposer 1 gets reviewer 0.
Example 3 — Three-way Matching
$ Input: proposerPrefs = [[2,1,0],[0,1,2],[1,0,2]], reviewerPrefs = [[1,0,2],[2,1,0],[0,1,2]]
Output: [1,0,2]
💡 Note: After the proposal process: P0→R1, P1→R0, P2→R2. This creates a stable matching with no blocking pairs.

Constraints

  • 2 ≤ n ≤ 1000
  • Both preference arrays have size n × n
  • Each preference list is a permutation of [0, 1, ..., n-1]
  • All preferences are complete and strict

Visualization

Tap to expand
INPUTALGORITHMRESULTP0: [1,2,0]P1: [2,0,1]P2: [0,1,2]Proposer PrefsR0: [2,1,0]R1: [0,2,1]R2: [1,0,2]Reviewer Prefs1Initialize unmatched queue2Proposers make offers3Reviewers accept/upgrade4Repeat until stableFinal MatchingP0 → R1P1 → R0P2 → R2Output: [1,0,2]No blocking pairs existMatching is stable!Key Insight:The Gale-Shapley algorithm lets proposers pursue preferences while reviewers upgradewhen possible. Instability naturally self-corrects through the proposal process, guaranteeingconvergence to a stable matching without testing invalid combinations.TutorialsPoint - Stable Matching (Gale-Shapley) | Gale-Shapley Algorithm
Asked in
Google 15 Microsoft 12 Meta 8 Amazon 6
12.5K Views
Medium Frequency
~45 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen