Python 2085.py
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
# count words
freq1 = defaultdict(int)
for w in words1:
freq1[w] += 1
freq2 = defaultdict(int)
for w in words2:
if w in freq1: # this "if" makes it a tiny bit faster
freq2[w] += 1
# find unique words in first word list
unique1 = set([ f for f in freq1 if freq1[f] == 1 ])
# must be in both sets
return sum([ 1 for f in freq2 if freq2[f] == 1 and f in unique1 ])
Difficulty
and has an acceptance rate of about 74% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of counting words that appear exactly once in each of two input lists. It proceeds in three logical phases: building a frequency map for the first list, selectively populating a second frequency map for words that also exist in the first map, and finally determining the intersection of uniquely-occurring words from both lists. The code is concise, leverages Python’s defaultdict for automatic counter initialization, and includes a small early-exit check that reduces unnecessary work when processing the second list.
Counting frequencies in the first list
The first phase creates a dictionary that records how many times each word appears in words1. By using defaultdict(int), the code avoids explicit existence checks before incrementing a count.
freq1 = defaultdict(int)
for w in words1:
freq1[w] += 1
This step ensures that every word from the first list is represented in freq1 with an accurate count, which later enables the identification of words that occur exactly once.
Selective counting in the second list
When iterating over words2, the implementation only updates a second frequency dictionary if the current word is already present in freq1. The conditional if w in freq1 acts as a filter that prevents the creation of entries for words that could never satisfy the final uniqueness condition, thereby saving both time and memory.
freq2 = defaultdict(int)
for w in words2:
if w in freq1: # tiny performance gain
freq2[w] += 1
Because the check is performed before the increment, the dictionary freq2 contains counts only for words that have a chance to be counted in the final result.
Isolating uniquely occurring words from the first list
After the two frequency maps are built, the code extracts the subset of words from freq1 whose count equals one. This is done with a set comprehension, which provides O(1) membership tests for the later intersection step.
unique1 = set([f for f in freq1 if freq1[f] == 1])
The resulting set, unique1, holds precisely those words that appear a single time in words1.
Computing the final count
The final expression iterates over the keys of freq2, selecting those that both appear exactly once in words2 (freq2[f] == 1) and belong to the previously computed unique1 set. The sum function aggregates a 1 for each qualifying word, yielding the total count.
return sum([1 for f in freq2 if freq2[f] == 1 and f in unique1])
Because the comprehension is evaluated lazily within sum, the code avoids constructing an intermediate list of boolean values.
Edge cases handled
The algorithm gracefully handles several edge conditions without additional branching:
- Empty input lists - If either
words1orwords2is empty, the corresponding frequency dictionary remains empty, and the final sum evaluates to zero. - All duplicate entries - When a word appears multiple times in either list, its count exceeds one, causing it to be excluded from the unique-word set or the final sum.
- Words exclusive to one list - A word that exists only in
words2never passes theif w in freq1guard, so it never contributes tofreq2and cannot affect the result. - Identical words in both lists but with differing frequencies - The intersection logic requires a count of exactly one in both dictionaries, ensuring that only perfectly matched unique occurrences are counted.
Performance optimizations observed
Several deliberate choices improve the runtime characteristics of the solution:
- Use of
defaultdict(int)eliminates explicit key existence checks during counting, reducing the overhead of dictionary lookups. - Early filter on the second list (
if w in freq1) prevents unnecessary increments and dictionary entries for words that cannot satisfy the final condition, cutting down both time spent in the loop and memory consumption. - Set for unique words provides constant-time membership tests when evaluating the final condition, making the intersection step efficient even for large dictionaries.
- Single pass per input list ensures that each list is traversed only once, avoiding redundant scans.
- Summation with a generator-style comprehension avoids building an auxiliary list of intermediate results, keeping the memory footprint minimal.
Overall, the code combines clear logical separation with targeted micro-optimizations that together yield an efficient solution for the unique-word counting problem.
ELI5 - Simplified Explanation
Imagine there are two big boxes filled with toy blocks, and each block has a word written on it. The goal is to find out how many words appear exactly one time in the first box and also exactly one time in the second box.
First, the code looks through the first box and sorts all the blocks into little piles based on their words to keep track of how many of each word exist. After that, the code does the same thing for the second box, but it only keeps the words that were also found in the first box to save time.
Next, the code picks out only those words from the first pile that showed up once and once only. Then, it checks the second pile to see which of those same words also showed up just one single time. When a word is found to be a lonely one in both boxes, it gets counted. By the end, all those special words are added up to see the final number.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 349: Intersection of Two Arrays
- problem 884: Uncommon Words from Two Sentences
- problem 2053: Kth Distinct String in an Array
Solved On The Same Day
- problem 1945: Sum of Digits of String After Convert
- problem 2078: Two Furthest Houses With Different Colors
- problem 1911: Maximum Alternating Subsequence Sum
- problem 2087: Minimum Cost Homecoming of a Robot in a Grid
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality