Count Pairs Of Similar Strings - Bitmasks & Hashmap [JS]

Description 

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 wordsm = 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]