DEV Community 👩‍💻👨‍💻

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Count Common Words With One Occurrence

`Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:

  • "leetcode" appears exactly once in each of the two arrays. We count this string.
  • "amazing" appears exactly once in each of the two arrays. We count this string.
  • "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
  • "as" appears once in words1, but does not appear in words2. We do not count this string. Thus, there are 2 strings that appear exactly once in each of the two arrays. `
/**
 * @param {string[]} words1
 * @param {string[]} words2
 * @return {number}
 */
var countWords = function (words1, words2) {
  let mapW1 = new Map();
  let mapW2 = new Map();

  for (let i = 0; i < words1.length; i++) {
    if (mapW1.has(words1[i])) {
      mapW1.set(words1[i], mapW1.get(words1[i] + 1));
    } else {
      mapW1.set(words1[i], 1);
    }
  }

  for (let i = 0; i < words2.length; i++) {
    if (mapW2.has(words2[i])) {
      mapW2.set(words2[i], mapW2.get(words2[i] + 1));
    } else {
      mapW2.set(words2[i], 1);
    }
  }
  let count = 0;

  for (let i = 0; i < words1.length; i++) {
    console.log(words1[i]);
    if (
      mapW1.has(words1[i]) &&
      mapW2.has(words1[i]) &&
      mapW1.get(words1[i]) === 1 &&
      mapW2.get(words1[i]) === 1
    ) {
      count++;
    }
  }
  return count;
};

console.log(
  countWords(
    ["leetcode", "is", "amazing", "as", "is"],
    ["amazing", "leetcode", "is"]
  )
);

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dawnpickle profile image
DawnPickle

This content is very helpful for all the users. how to break up a couple from a distance

We're hiring!

We're Hiring

We're looking for a Senior Full Stack Engineer to join the DEV team.

Head here to learn more.