Given two string arrays words1
and words2
, return the number of strings that appear exactly once in each of the two arrays.
Example 1:
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.
Example 2:
Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] Output: 0 Explanation: There are no strings that appear in each of the two arrays.
Example 3:
Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"] Output: 1 Explanation: The only string that appears exactly once in each of the two arrays is "ab".
Constraints:
1 <= words1.length, words2.length <= 1000
1 <= words1[i].length, words2[j].length <= 30
words1[i]
and words2[j]
consists only of lowercase English letters.This problem requires finding the number of words that appear exactly once in both input arrays, words1
and words2
. The most efficient approach uses hash tables (or dictionaries in Python) to count word occurrences in each array.
Algorithm:
Count Occurrences: Two hash tables (or dictionaries) are used: cnt1
for words1
and cnt2
for words2
. Each table stores words as keys and their counts as values. We iterate through each array, updating the counts in the corresponding hash table. For example, if a word is already present, its count is incremented; otherwise, it's added with a count of 1.
Find Common Words with Single Occurrences: We iterate through the keys (words) of cnt1
. For each word, we check two conditions:
cnt1
is 1 (cnt1[word] == 1
).cnt2
is also 1 (cnt2[word] == 1
or cnt2.get(word,0) == 1
in languages that handle missing keys differently).Increment Count: If both conditions are true, it means the word appears exactly once in both arrays, and we increment a counter ans
.
Return Count: Finally, we return the value of ans
, representing the total number of common words with single occurrences.
Time Complexity: O(m + n), where m is the length of words1
and n is the length of words2
. This is because we iterate through each array once to build the hash tables and then iterate through one hash table (which has at most the size of the smaller array) to find the common words. Hash table lookups are O(1) on average.
Space Complexity: O(m + n) in the worst case. This is because the hash tables could store all unique words from both arrays if all words are unique.
Code Examples (with detailed explanations):
Python:
from collections import Counter
class Solution:
def countWords(self, words1: list[str], words2: list[str]) -> int:
"""
Counts common words with one occurrence in two arrays.
Args:
words1: The first array of strings.
words2: The second array of strings.
Returns:
The number of common words with exactly one occurrence in each array.
"""
# Using Counter for efficient counting
cnt1 = Counter(words1) # Creates a dictionary with word counts for words1
cnt2 = Counter(words2) # Creates a dictionary with word counts for words2
ans = 0 # Initialize the count of common words
for word, count in cnt1.items(): # Iterate through words and their counts in cnt1
if count == 1 and cnt2[word] == 1: # Check if count is 1 in both dictionaries
ans += 1 # Increment the count if the word appears once in both
return ans
Java:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int countWords(String[] words1, String[] words2) {
Map<String, Integer> cnt1 = new HashMap<>();
Map<String, Integer> cnt2 = new HashMap<>();
// Count occurrences in words1
for (String word : words1) {
cnt1.put(word, cnt1.getOrDefault(word, 0) + 1);
}
// Count occurrences in words2
for (String word : words2) {
cnt2.put(word, cnt2.getOrDefault(word, 0) + 1);
}
int ans = 0;
for (Map.Entry<String, Integer> entry : cnt1.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
if (count == 1 && cnt2.getOrDefault(word, 0) == 1) {
ans++;
}
}
return ans;
}
}
The Java and other language examples follow a similar structure, utilizing hash map data structures to achieve the same efficient counting and comparison. The key is the use of hash tables for O(1) average-case lookup time.