Problem 2085

Abstract / Summary

Count words that appear exactly once in both strings and are the same in both.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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 ])
16 lines | 582 bytes | submitted February 5, 2024 | GitHub   36% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 words1 or words2 is 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 words2 never passes the if w in freq1 guard, so it never contributes to freq2 and 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.85 | σ = 0.66

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 13 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

5 solutions   February 5, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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