Problem 442

Abstract / Summary

Given a list of integers where each value is between one and the list length inclusive and all values appear once except some which appear twice find all numbers that appear twice.

Note

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

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
8 lines | 288 bytes | submitted October 5, 2023 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sorting
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 4.70 | σ = 2.29

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
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++
44 links | 31 authors | 10 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

8 medium 1 hard
10 solutions   October 5, 2023

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