-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
66 lines (53 loc) · 1.63 KB
/
Copy pathsolution.js
File metadata and controls
66 lines (53 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @param {number[][]} men
* @param {number[][]} women
* @returns {number[]}
*/
class Solution {
stableMarriage(men, women) {
const n = men.length;
// rank[w][m] = preference rank of man m for woman w
const rank = Array.from({ length: n }, () => Array(n).fill(0));
for (let w = 0; w < n; w++) {
for (let pos = 0; pos < n; pos++) {
rank[w][women[w][pos]] = pos;
}
}
// womanPartner[w] = current man matched with woman w
const womanPartner = Array(n).fill(-1);
// result[m] = woman matched with man m
const result = Array(n).fill(-1);
// nextProposal[m] = next woman index to propose
const nextProposal = Array(n).fill(0);
const freeMen = [];
// Initially all men are free
for (let i = 0; i < n; i++) {
freeMen.push(i);
}
while (freeMen.length > 0) {
const man = freeMen.shift();
// Next preferred woman
const woman = men[man][nextProposal[man]];
nextProposal[man]++;
// If woman is free
if (womanPartner[woman] === -1) {
womanPartner[woman] = man;
result[man] = woman;
} else {
const currentMan = womanPartner[woman];
// If woman prefers new man
if (rank[woman][man] < rank[woman][currentMan]) {
womanPartner[woman] = man;
result[man] = woman;
// Old partner becomes free
result[currentMan] = -1;
freeMen.push(currentMan);
} else {
// Woman rejects the proposal
freeMen.push(man);
}
}
}
return result;
}
}