Problem 2032

Abstract / Summary

Given three integers, return the sum of the two largest numbers.

Note

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

Python 2032.py

class Solution:
    def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
        freq = defaultdict(int)
        for n in set(nums1):
            freq[n] += 1
        for n in set(nums2):
            freq[n] += 1
        for n in set(nums3):
            freq[n] += 1

        for f in freq:
            if freq[f] >= 2:
                yield f
13 lines | 396 bytes | submitted January 27, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
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 defines a Solution class with a method twoOutOfThree that receives three integer arrays. Its purpose is to identify all distinct values that appear in at least two of the three input collections. The method builds a frequency map that records how many of the three arrays contain each value, then lazily yields the qualifying numbers.

Core Logic

At the heart of the algorithm is a three-stage process: deduplicate each input list, update a shared counter, and emit values whose counter meets the threshold of two. The use of a generator (yield) means the caller can iterate over results without requiring an intermediate list.

def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
    freq = defaultdict(int)
    ...
    for f in freq:
        if freq[f] >= 2:
            yield f

Frequency Accumulation

The method first creates a defaultdict of integers to serve as the frequency table. For each of the three input arrays, it constructs a set to eliminate duplicate occurrences within the same array. Each unique element from the set increments its entry in the dictionary by one. This ensures that an element contributed at most once per source array, regardless of how many times it appears inside that array.

freq = defaultdict(int)
for n in set(nums1):
    freq[n] += 1
for n in set(nums2):
    freq[n] += 1
for n in set(nums3):
    freq[n] += 1

Result Generation

After the frequency map is populated, the method iterates over its keys. Whenever a key’s count is two or greater, the value is produced via yield. Because yield creates a generator, the caller can consume results one by one, which is especially useful when only a subset of the output is needed.

for f in freq:
    if freq[f] >= 2:
        yield f

Edge Cases Handled

The algorithm gracefully manages several boundary conditions:

  • Empty input arrays - If any of the three lists is empty, converting it to a set yields an empty collection, so no increments occur for that source. The remaining arrays are still processed correctly.
  • All three arrays identical - Each distinct element will be added to the set three times, resulting in a frequency of three. Since three satisfies the “at least two” condition, every unique element is yielded exactly once.
  • Elements appearing in exactly two arrays - The frequency for such elements becomes two, meeting the threshold, and they are emitted.
  • Elements appearing in only one array - Their frequency remains one, so they are excluded from the output.
  • Negative numbers and zero - The dictionary keys accept any hashable integer, so negative values and zero are treated identically to positive numbers.
  • Large numeric ranges - Because the dictionary stores only distinct values that actually appear, the memory footprint scales with the number of unique elements rather than the numeric magnitude.

Performance Considerations

The implementation incorporates several optimizations that keep execution efficient:

  • Deduplication via set - By converting each input list to a set before counting, the algorithm avoids counting repeated occurrences within the same list. This reduces the number of dictionary updates, especially when an input contains many duplicates.
  • Constant-time updates with defaultdict - The use of a defaultdict(int) eliminates the need for explicit existence checks before incrementing a counter, allowing each update to proceed in a single operation.
  • Lazy result production - Employing yield creates a generator that produces values on demand. This avoids constructing an intermediate list of results, saving both time and memory when the caller consumes only part of the output or streams it directly.
  • Single pass over the frequency map - After the three accumulation loops, the method makes one linear scan of the dictionary keys to filter qualifying elements, ensuring that no extra passes over the original data are required.
written by openai gpt

ELI5 - Simplified Explanation

Imagine three buckets filled with colorful number blocks. The goal is to find all the numbers that appear in at least two of those buckets.

A special tally sheet starts out empty. First, look at the first bucket and pick out one of each number found inside, then put a mark next to that number on the tally sheet. Do the same thing for the second bucket and add another mark to the tally sheet if you see the same number again. Repeat this one more time for the third bucket.

After everything is marked, look at the tally sheet. Any number that has two or more marks next to it is a winner because it was found in at least two different buckets. You just point to those winning numbers to show them off.

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 | μ = 7.00 | σ = 1.30

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
26 links | 14 authors | 9 languages

Videos

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

Solved On The Same Day

5 solutions   January 27, 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