const findFirstCoalescingSetAmongGroupOfSets = array => {
const indices = array.reduce((m, a, i) => {
a.forEach(v => m.set(v, [...(m.get(v) || []), i]));
return m;
}, new Map); // map values to indecies in original array of arrays
const p2 = Array.from(indices.keys()).reduce((m, v, i) => m.set(v, i), new Map); // map values to indecies in indices
const p2i = new Map(Array.from(p2).map(([k,v]) => [v, k])); // map indecies to values in indices
const n = array.length, k = p2.size; // n - vertices in original array indecies partile, k - vertices in all possible values partile
const g = array.map(e => e.map(v => p2.get(v))); // adjacency lists of a bipartite graph
const mt = new Array(k).fill(-1); // mt[i] - index of vertice from first partile connected with ith vertice from second partile, or -1
let used; // temporary array to fix attended vertices during recursion
// in recursion we got around unattended vertices of first graph partile trying to enlarge chain of vertices pairs (to, mt[to]) for each new vertice from first graph partile
const try_kuhn = v => {
if (used[v]) return false;
used[v] = true;
for (let i = 0; i < g[v].length; ++i) {
const to = g[v][i];
if (mt[to] === -1 || try_kuhn(mt[to])) {
mt[to] = v;
return true;
}
}
return false;
}
for (let v = 0; v < n; ++v) {
used = new Array(n).fill(false);
try_kuhn(v);
}
const result = new Array(n);
for (let i = 0; i < k; ++i) {
if (mt[i] != -1) {
result[mt[i]] = p2i.get(i);
}
}
//console.log("array =", array);
//console.log("indices=", indices);
//console.log("p2=", p2);
//console.log("p2i=", p2i);
//console.log("g=", g);
for (let i = 0; i < n; ++i) {
if (result[i] === undefined) return;
}
return result;
}
console.log(findFirstCoalescingSetAmongGroupOfSets([[4], [1, 2, 3, 4], [2, 3], [1]]));
console.log(findFirstCoalescingSetAmongGroupOfSets([[1, 3, 4], [2, 3, 4], [1, 2], [1, 2, 3, 4]]));
console.log(findFirstCoalescingSetAmongGroupOfSets([[1, 3], [2, 3], [1, 2]]));
console.log(findFirstCoalescingSetAmongGroupOfSets([[1, 2, 3, 4, 5], [1], [1]]));
console.log(findFirstCoalescingSetAmongGroupOfSets([[1, 2, 3], [1, 2], [1, 2]]));