Question:

image.png

Stable Matching ?

a matching is stable if there is no pair

(man,woman)

who are not married to each other but both prefer each other over their current partners.

The Gale-Shapley Algorithm (Men-Proposing)

Since the problem asks for the result from the men's perspective, we will implement the version where men propose to women.

  1. Initialize: All men and women are initially "free" (not engaged).
  2. Loop: While there is a free man who still has women he hasn't proposed to:
  3. Result: When everyone is paired up, the resulting matching is guaranteed to be stable and man-optimal.

Approach: Two-Pointer Technique

  1. Initialize two pointers: left at the beginning of the array (index 0) and right at the end of the array (index ).

    n−1
    
  2. While left is less than right:

Alternative Approach: Counting (Simpler)

Another simple

O(N)

way is to count the number of zeros and then overwrite the array.