function getIntersection(sets) {
let result = []; // To store the resultant set
let smallSetInd = 0; // Initialize index of smallest set
let minSize = sets[0].length; // Initialize size of smallest set
// sort all the sets, and also find the smallest set
for (let i = 1; i < sets.length; i++) {
// sort this set
sets[i].sort((a, b) => a - b);
// update minSize, if needed
if (minSize > sets[i].length) {
minSize = sets[i].length;
smallSetInd = i;
}
}
let elementsMap = new Map();
// Add all the elements of smallest set to a map, if already present,
// update the frequency
for (let i = 0; i < sets[smallSetInd].length; i++) {
let elem = sets[smallSetInd][i];
if (!elementsMap.has(elem)) {
elementsMap.set(elem, 1);
} else {
elementsMap.set(elem, elementsMap.get(elem) + 1);
}
}
// iterate through the map elements to see if they are present in
// remaining sets
for (let [elem, freq] of elementsMap) {
let bFound = true;
// Iterate through all sets
for (let j = 0; j < sets.length; j++) {
// If this set is not the smallest set, then do binary search in it
if (j !== smallSetInd) {
// If the element is found in this set, then find its frequency
if (sets[j].includes(elem)) {
let lInd = sets[j].indexOf(elem);
let rInd = sets[j].lastIndexOf(elem) + 1;
// Update the minimum frequency, if needed
if ((rInd - lInd) < freq) {
freq = rInd - lInd;
}
// If the element is not present in any set, then no need
// to proceed for this element.
} else {
bFound = false;
break;
}
}
}
// If element was found in all sets, then add it to result 'freq' times
if (bFound) {
for (let i = 0; i < freq; i++) {
result.push(elem);
}
}
}
return result;
}
// A utility function to print a set of elements
function printSet(s) {
console.log(s.join(" "));
}
// Test case
function testCase1() {
let sets = [ [1, 1, 2, 2, 5],
[1, 1, 4, 3, 5, 9],
[1, 1, 2, 3, 5, 6]
];
let r = getIntersection(sets);
printSet(r);
}
// Driver program to test above functions
testCase1();