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 whereproposerPrefs[i]is proposeri's preference list (most preferred first)reviewerPrefs: 2D array wherereviewerPrefs[i]is revieweri'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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code