JJobsMoi
Jane Street
JA

Count Common Words With One Occurrence

Codingeasy

Problem

You are given two arrays of strings, words1 and words2.

A string w is considered a match if it appears in words1 exactly once and also appears in words2 exactly once. Return the number of distinct strings that satisfy this match condition.

Notes:

  • A word that shows up twice or more in either array can never count as a match, even if it also shows up once in the other array.
  • Comparisons are exact string comparisons (case-sensitive), and each qualifying word is counted only once regardless of how many times it would otherwise repeat.

Examples

Example 1:

Input: words1 = ["kite","echo","echo","lamp"], words2 = ["lamp","kite","drum"]

Output: 2

Explanation:

  • "kite" appears once in words1 and once in words2 — counts.
  • "echo" appears twice in words1, so it is disqualified even though it's absent from words2.
  • "lamp" appears once in words1 and once in words2 — counts.
  • "drum" only appears in words2, so it doesn't matter how many times — no match in words1.

Total matches: "kite" and "lamp", so the answer is 2.

Example 2:

Input: words1 = ["cat","cat","dog"], words2 = ["dog","dog","cat"]

Output: 0

Explanation:

  • "cat" appears twice in words1, so it fails the exactly-once rule for words1.
  • "dog" appears once in words1 but twice in words2, so it fails the exactly-once rule for words2.

No word satisfies both conditions, so the answer is 0.

Constraints

  • 1 <= words1.length, words2.length <= 1000
  • 1 <= words1[i].length, words2[j].length <= 30
  • Each word consists of lowercase English letters only.

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate