1002. Find Common Characters
202410122105
tags: #hash-map
const toMap = (word) => {
const map = new Map();
for (const c of word) {
map.set(c, (map.get(c) ?? 0) + 1);
}
return map;
}
const intersect = (map1, map2) => {
const set = new Set([...map1.keys()].concat([...map2.keys()]));
const newMap = new Map();
for (const key of set) {
const intersectCount = Math.min(map1.get(key) ?? 0, map2.get(key) ?? 0);
if (intersectCount !== 0) {
newMap.set(key, intersectCount);
}
}
return newMap;
}
var commonChars = function(words) {
let wordMap = toMap(words[0]);
for (let i = 1; i < words.length; i++) {
wordMap = intersect(wordMap, toMap(words[i]));
}
const res = [];
for (const [key, val] of wordMap.entries()) {
for (let i = 0; i < val; i++) {
res.push(key);
}
}
return res;
};