02

Stable Matching Problem

Chapter 2 • Intermediate

90 min

Stable Matching Problem

Problem Statement

Given two sets of equal size (e.g., medical students and hospitals), each with preferences, find a stable matching where no pair would prefer each other over their current match.

Key Properties

  • Stability: No two elements prefer each other over their current partners
  • Perfect Matching: Every element is matched
  • Uniqueness: There may be multiple stable matchings

Gale-Shapley Algorithm

The Gale-Shapley algorithm guarantees a stable matching.

Algorithm Steps

  1. Initialize all elements as free
  2. While there exists a free element with untried preferences:
  • Propose to the highest-ranked untried preference
  • If the preference is free, they become engaged
  • If the preference is engaged but prefers this proposal, switch engagement
  • Otherwise, reject the proposal
  1. Return the matching

Implementation

python.js
def gale_shapley(students, hospitals):
    """
    Gale-Shapley algorithm for stable matching.
    Time: O(n²), Space: O(n)
    """
    n = len(students)
    # Track current proposals
    student_proposals = [0] * n
    # Track current engagements
    hospital_partners = [-1] * n
    # Track if student is free
    student_free = [True] * n
    
    while any(student_free):
        # Find a free student
        student = next(i for i in range(n) if student_free[i])
        
        if student_proposals[student] >= len(students[student]):
            break  # No more preferences
        
        # Get next preferred hospital
        hospital = students[student][student_proposals[student]]
        student_proposals[student] += 1
        
        if hospital_partners[hospital] == -1:
            # Hospital is free, engage
            hospital_partners[hospital] = student
            student_free[student] = False
        else:
            # Check if hospital prefers this student
            current_student = hospital_partners[hospital]
            if hospitals[hospital].index(student) < hospitals[hospital].index(current_student):
                # Hospital prefers new student
                hospital_partners[hospital] = student
                student_free[student] = False
                student_free[current_student] = True
    
    return hospital_partners

Applications

  • Medical residency matching
  • College admissions
  • Job matching
  • Dating apps
  • Resource allocation

Properties

  • Termination: Algorithm always terminates
  • Correctness: Produces a stable matching
  • Optimality: Students get their best possible stable match
  • Time Complexity: O(n²)

Practice Problems

  1. Implement Gale-Shapley for 10 students and 10 hospitals
  2. Find all stable matchings for a small instance
  3. Modify algorithm for one-to-many matching
  4. Analyze worst-case scenario