Python 0442.py
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
# "constant extra space" => let's have always 10^5 extra space
count = [ 0 ] * 100001
for n in nums:
count[n] += 1
if count[n] > 1:
yield n
Difficulty
and has an acceptance rate of about 77% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Sorting
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 defines a Solution class with a method findDuplicates that receives a list of integers and produces the values that appear more than once. The method relies on a pre-allocated auxiliary array to count occurrences and uses a generator (yield) to emit each duplicate as soon as it is detected. This approach keeps the additional memory footprint fixed and avoids constructing an intermediate collection of results.
Key Steps
Allocation of a counting buffer
count = [0] * 100001
A list named count is created with a length of 100 001, each element initialized to zero. The size matches the assumed maximum value that can appear in the input list, allowing direct indexing by the integer values themselves. This eliminates the need for hash-based structures and provides constant-time access for incrementing counters.
Linear traversal of the input
for n in nums:
count[n] += 1
if count[n] > 1:
yield n
The method iterates over every element n in the supplied nums. For each element, the corresponding slot in count is incremented. Immediately after the increment, the code checks whether the counter exceeds one. If it does, the current value n is emitted via yield. Because yield turns the function into a generator, duplicates are produced on-the-fly without storing them in a separate list.
Edge Cases Handled
When the input list is empty, the for loop body never executes, and the generator produces no output, which correctly represents the absence of duplicates.
If an element appears more than twice, the condition count[n] > 1 remains true for every subsequent occurrence, causing the same duplicate value to be yielded each time it is encountered after the first repetition. This behavior ensures that every repeated occurrence is reported, matching the semantics of a generator that streams duplicates as they are discovered.
The pre-allocated buffer size of 100 001 implicitly bounds the acceptable range of input values. Values that fall within 0 to 100000 are safely indexed; any value outside this range would raise an IndexError, which the code implicitly treats as an out-of-bounds scenario.
Performance Optimizations
The algorithm avoids dynamic data structures such as dictionaries or sets, opting instead for a fixed-size list that provides O(1) random access. This choice reduces overhead associated with hashing and memory allocation during the scan.
By using a generator (yield) rather than accumulating results in a list, the method minimizes peak memory usage. The caller can consume duplicates one at a time, which is especially beneficial when the number of duplicates is large relative to the input size.
Pre-initializing the counting buffer with a known size also sidesteps repeated resizing operations that would occur if the buffer grew adaptively. The single allocation at the start of the method contributes to predictable performance characteristics throughout the execution.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks. Some of the numbers appear more than once, and finding the doubles can be a bit tricky if you just look at them all at once. To solve this, you get a special piece of paper with a very long row of empty checkboxes, one for every number that might be on a block.
You go through the pile of blocks one by one. You pick up a block, look at the number on it, and go to the spot on your paper that matches that number. You color in one box there to show you found that number. If you pick up another block and see the same number, you check your paper and see that the box is already colored. That is how you know you have found a repeat. Every time you see a box already filled in, you set that block aside on a special plate because it is a duplicate.
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 | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | AdelDaniel | Dart | |||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| AdelDaniel | Dart | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| pruthvikp | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 448: Find All Numbers Disappeared in an Array
- problem 2615: Sum of Distances
Solved On The Same Day
- problem 417: Pacific Atlantic Water Flow
- problem 457: Circular Array Loop
- problem 554: Brick Wall
- problem 565: Array Nesting
- problem 647: Palindromic Substrings
- problem 721: Accounts Merge
- problem 785: Is Graph Bipartite?
- problem 1061: Lexicographically Smallest Equivalent String
- problem 273: Integer to English Words
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