Count Pairs Of Similar Strings - Bitmasks & Hashmap [JS]
Solution: Bitmasks & Hashmap
Since there are only 26 lowercase characters, we can keep track of each word's unique characters in a bitmask.
Use a hashmap to count the number of occurances of each bitmask.
From the occurances of each bitmask, we can find the number of similar pairs.
n = number of words
, m = max(words[i].length)
Time Complexity: O(nm)
105ms
Space Complexity: O(n)
44.9MB
var similarPairs = function(words) {
let count = new Map(), ans = 0;
for (let word of words) {
let mask = getMask(word);
let occurances = count.get(mask) || 0;
ans += occurances;
count.set(mask, occurances + 1);
}
return ans;
};
function getMask(word) {
let mask = 0;
for (let i = 0; i < word.length; i++) {
let charcode = word[i].charCodeAt() - 97;
mask |= (1 << charcode);
}
return mask;
}
Comments
Post a Comment