You are given two string arrays words1
and words2
. A word is common if it appears in both arrays. A common word is considered to have “one occurrence” if it appears exactly once in each of the given arrays.
Your task is to return the number of common words with one occurrence.
words1
and words2
? (0 ≤ len(words1), len(words2) ≤ 1000)words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
2
words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
0
Here’s the Python code to solve the problem:
from collections import Counter
def countWords(words1, words2):
# Count the frequency of each word in both lists
count1 = Counter(words1)
count2 = Counter(words2)
# Initialize count of common words with exactly one occurrence
common_one_occurrence = 0
# Iterate through the words in count1
for word in count1:
# Check if the word has exactly one occurrence in both count1 and count2
if count1[word] == 1 and count2[word] == 1:
common_one_occurrence += 1
return common_one_occurrence
# Example Usage
words1 = ["leetcode","is","amazing","as","is"]
words2 = ["amazing","leetcode","is"]
print(countWords(words1, words2)) # Output: 2
Counter
class from the collections
module to count how many times each word appears in both words1
and words2
.count1
).count1
and count2
.n
is the length of words1
and m
is the length of words2
.words1
and words2
.count1
, which in the worst-case scenario, could be O(n).Overall, the solution has a time complexity of O(n + m) where n
and m
are the lengths of words1
and words2
, respectively. This is efficient given the input constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?