LeetCode 2085: Count Common Words With One Occurrence Solution

Master LeetCode problem 2085 (Count Common Words With One Occurrence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2085. Count Common Words With One Occurrence

Problem Explanation

Explanation

To solve this problem, we can iterate through both input arrays words1 and words2 and count the frequency of each word in each array using HashMaps. Then, we can iterate through the words in both arrays and check if a word appears exactly once in each array. If it does, we increment a counter. Finally, we return the counter as the result.

  • Create HashMaps to store the frequency of words in words1 and words2.
  • Iterate through both arrays and count the frequency of words.
  • Iterate through the words in both arrays and check if a word appears exactly once in each array.
  • Increment a counter for each word that meets the condition.
  • Return the counter as the result.

Time complexity: O(m + n) where m is the size of words1 and n is the size of words2. Space complexity: O(m + n) for storing the frequency of words in both arrays.

Solution Code

import java.util.HashMap;

class Solution {
    public int countCommonWords(String[] words1, String[] words2) {
        HashMap<String, Integer> freq1 = new HashMap<>();
        HashMap<String, Integer> freq2 = new HashMap<>();
        
        for (String word : words1) {
            freq1.put(word, freq1.getOrDefault(word, 0) + 1);
        }
        
        for (String word : words2) {
            freq2.put(word, freq2.getOrDefault(word, 0) + 1);
        }
        
        int count = 0;
        for (String word : freq1.keySet()) {
            if (freq1.get(word) == 1 && freq2.getOrDefault(word, 0) == 1) {
                count++;
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2085 (Count Common Words With One Occurrence)?

This page provides optimized solutions for LeetCode problem 2085 (Count Common Words With One Occurrence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2085 (Count Common Words With One Occurrence)?

The time complexity for LeetCode 2085 (Count Common Words With One Occurrence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2085 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2085 in Java, C++, or Python.

Back to LeetCode Solutions