Number of Valid Words for Each Puzzle LeetCode solution in JavaScript

1
var findNumOfValidWords = function (words, puzzles) {
2
// Form map of word's bitmasks
3
const wordsMaskMap = words.reduce(
4
(map, word) => addToMap(map, getMask(word)),
5
new Map()
6
);
7

8
return puzzles.map((puzzle) => {
9
const pMask = getMask(puzzle);
10
const pFirstMask = getFirstMask(puzzle);
11
let count = 0;
12

13
// Verify each bitmask against a given puzzle
14
for (let wMask of wordsMaskMap.keys()) {
15
if (wMask & pFirstMask && !((wMask | pMask) ^ pMask)) {
16
count += wordsMaskMap.get(wMask);
17
}
18
}
19
return count;
20
});
21
};
22

23
// Transform a char into a bit index
24
var getBit = (char) => 1 << (char.charCodeAt(0) - "a".charCodeAt(0));
25

26
// Transform a word into a bitmask
27
var getMask = (word) => word.split("").reduce((acc, c) => acc | getBit(c), 0);
28

29
// Get a bitmask for the first letter of a word
30
var getFirstMask = (word) => getBit(word[0]);
31

32
// Helper function to count hashes in a Map object
33
var addToMap = (map, val) =>
34
map.has(val) ? map.set(val, map.get(val) + 1) : map.set(val, 1);

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0