Problem 287

Abstract / Summary

Given an array with numbers from one to n and one duplicate find the repeated value.

Note

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

C++ 0287.cpp

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        // cheating ...
        unordered_set<int> has;
        has.reserve(11000);
        for (auto n : nums)
        {
            if (has.count(n) > 0)
                return n;

            has.insert(n);
        }

        return -1;
    }
};
17 lines | 334 bytes | submitted August 8, 2023 | GitHub   7% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (4+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Bit Manipulation
  • Two Pointers
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 classic “find the duplicate number” problem by scanning the input array once while maintaining a hash-based container that records every value seen so far. As soon as a value is encountered that already exists in the container, the function returns that value as the duplicate. If the scan finishes without finding a repeat, the function returns -1.

Key Steps

Allocation of the hash container

The algorithm begins by creating an unordered_set<int> named has. Immediately after construction the code calls has.reserve(11000);. This call pre-allocates bucket space for roughly eleven thousand elements, which reduces the number of internal rehash operations when the set grows. The reservation is performed before any elements are inserted, ensuring that the container can accommodate a typical input size without costly expansions.

unordered_set<int> has;
has.reserve(11000);

Linear traversal of the input

The core of the solution is a range-based for loop that iterates over each integer n in the supplied vector nums. The loop processes elements in the order they appear, preserving the original sequence.

for (auto n : nums)
{
    // body omitted for brevity
}

Duplicate detection

Inside the loop the code checks whether the current element n is already present in the set by invoking has.count(n). The count method returns the number of occurrences of n in the set, which is either 0 or 1 because a set cannot hold duplicates. If the result is greater than zero, the function immediately returns n, signalling that a duplicate has been found.

if (has.count(n) > 0)
    return n;

Insertion of new elements

When the current element is not yet in the set, the algorithm inserts it using has.insert(n);. This operation adds the element to the hash table, making it available for future duplicate checks.

has.insert(n);

Fallback return

If the loop completes without triggering the early return, the function reaches the final statement return -1;. This return value indicates that no duplicate was detected during the scan, which can happen when the input does not satisfy the problem’s guarantee of at least one repeated element.

return -1;

Edge Cases Handled

The implementation gracefully handles an empty vector because the loop body is never executed, and the function proceeds directly to the fallback return of -1. When the duplicate appears as the very first element examined, the has.count check fails for the initial occurrence, the element is inserted, and the subsequent identical element triggers the immediate return. If the duplicate resides at the end of the array, the algorithm continues inserting each distinct value until the final element matches one already stored, at which point it returns the duplicate. The use of an unordered_set<int> also accommodates the full range of signed 32-bit integers, so both positive and negative values are processed without special handling.

Performance Optimizations

The explicit reservation of bucket space (has.reserve(11000)) is a notable optimization. By allocating sufficient capacity up front, the code avoids repeated rehashing and memory allocation that would otherwise occur as the set grows during insertion. This pre-allocation improves cache locality and reduces the overhead associated with dynamic resizing.

The choice of unordered_set provides average-case constant-time operations for both the membership test (count) and the insertion (insert). Because the algorithm performs exactly one membership test and, when necessary, one insertion per element, the overall work done per element remains minimal.

Early termination is another performance benefit. As soon as a duplicate is discovered, the function exits, preventing any further unnecessary processing of the remaining elements. This behavior is especially advantageous for inputs where the duplicate appears early in the sequence.

Overall, the combination of pre-allocation, hash-based constant-time operations, and early exit yields a solution that processes the input efficiently while using a straightforward and readable approach.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big basket full of numbered blocks. Some of the numbers might be exactly the same, and the goal is to find the one that shows up twice. To do this, think of a notebook where every page is empty at the start.

The code walks through the pile of blocks one by one. It picks up a block and looks at the number written on it. Then, it flips to the page in the notebook that matches that number. If the page is already filled with a little mark, it means that number was seen once before, which reveals that this specific block is the extra one being searched for.

If the page inside the notebook is still blank, it makes a little mark on it so that the notebook remembers seeing that number. It keeps checking every block in the pile until it spots the one that already has a mark waiting for it. Once that sneaky duplicate is found, the work is finished.

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 = 6 | μ = 6.04 | σ = 1.67

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 Rust Python JS Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github aylei Rust
BigEggStudy C#
black-shadows C++
bujosa Rust
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
FelixFan1122 C#
fpdjsns C++
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fpdjsns C++
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
pruthvikp Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
51 links | 35 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Find the Duplicate Number | With Proof | Follow Up Qns | Hare And Tortoise | Leetcode - 287'
codestorywithMIK 27 mins
Find the Duplicate Number | With Proof | Follow Up Qns | Hare And Tortoise | Leetcode - 287
YouTube video 'Find the Duplicate Number 🔥🔥| Arrays | Love Babbar DSA Sheet | Brute + Better + Optimal Approach'
Ayushi Sharma 15 mins
Find the Duplicate Number 🔥🔥| Arrays | Love Babbar DSA Sheet | Brute + Better + Optimal Approach
YouTube video 'Floyd’s Algorithm for Cycle Detection | LeetCode 287. Find the Duplicate Number | Part 2'
Shiran Afergan 10 mins
Floyd’s Algorithm for Cycle Detection | LeetCode 287. Find the Duplicate Number | Part 2
YouTube video '287. Find the Duplicate Number | Day 013 | 5 Ways | Binary Search | Bit Manipulation | Slow & Fast'
Aryan Mittal 41 mins
287. Find the Duplicate Number | Day 013 | 5 Ways | Binary Search | Bit Manipulation | Slow & Fast
YouTube video 'Find The Duplicate Number | Leetcode 287 | Arrays | O(N) Time Complexity #dsa'
Learn With Chirag 9 mins
Find The Duplicate Number | Leetcode 287 | Arrays | O(N) Time Complexity #dsa
YouTube video 'LEETCODE 287 (JAVASCRIPT) | FIND THE DUPLICATE NUMBER'
Andy Gala 13 mins
LEETCODE 287 (JAVASCRIPT) | FIND THE DUPLICATE NUMBER
YouTube video 'Find the Duplicate Number | Day 25 | Floyd's cycle | [June LeetCoding Challenge] [Leetcode #287]'
Algorithms Made Easy 5 mins
Find the Duplicate Number | Day 25 | Floyd's cycle | [June LeetCoding Challenge] [Leetcode #287]
YouTube video 'Find the Duplicate Number - Leetcode 287 - Python'
TechError 7 mins
Find the Duplicate Number - Leetcode 287 - Python
YouTube video 'Find the Duplicate Number | Leetcode 287 | 4 Approaches  🔥🔥 | Live coding session'
Coding Decoded 11 mins
Find the Duplicate Number | Leetcode 287 | 4 Approaches 🔥🔥 | Live coding session
YouTube video '287.  Find the Duplicate Number Leetcode Problem | Solution with Explanation | DSA Problem Series'
Coding Blocks 8 mins
287. Find the Duplicate Number Leetcode Problem | Solution with Explanation | DSA Problem Series
YouTube video '287. Find the Duplicate Number | Daily Leetcode Challenge | September | C++ | Java'
Mayur Programming Club 7 mins
287. Find the Duplicate Number | Daily Leetcode Challenge | September | C++ | Java
YouTube video 'Find the Duplicate Number: 287 - nvidia interview question'
Destination FAANG 14 mins
Find the Duplicate Number: 287 - nvidia interview question
YouTube video '287. Find the Duplicate Number - Fast & Slow Pointer - JavaScript'
LeetCodeWithMonu 19 mins
287. Find the Duplicate Number - Fast & Slow Pointer - JavaScript
YouTube video '287. Find the Duplicate Number | Java | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 5 mins
287. Find the Duplicate Number | Java | Leetcode | Arrays | Fundamentals
YouTube video 'Daily Leetcode #1454: Mar 24, 2024 - 287. Find the Duplicate Number'
Programming Live with Larry 11 mins
Daily Leetcode #1454: Mar 24, 2024 - 287. Find the Duplicate Number
YouTube video 'Daily Leetcode #1267: Sep 19, 2023 - 287. Find the Duplicate Number'
Programming Live with Larry 28 mins
Daily Leetcode #1267: Sep 19, 2023 - 287. Find the Duplicate Number
YouTube video 'Leetcode 287: Find the Duplicate Number in Telugu | Linear, Set, Floyd’s Cycle | srkcodes'
Srk Codes 8 mins
Leetcode 287: Find the Duplicate Number in Telugu | Linear, Set, Floyd’s Cycle | srkcodes
YouTube video 'Daily Leetcode #728: Mar 29, 2022 - 287. Find the Duplicate Number'
Programming Live with Larry 60 mins
Daily Leetcode #728: Mar 29, 2022 - 287. Find the Duplicate Number
YouTube video 'Daily Leetcode #86: Jun 25, 2020 - 287. Find the Duplicate Number'
Programming Live with Larry 17 mins
Daily Leetcode #86: Jun 25, 2020 - 287. Find the Duplicate Number
YouTube video 'Find the Duplicate Number (LeetCode 287) (Two Approaches)'
CodeWithARB 16 mins
Find the Duplicate Number (LeetCode 287) (Two Approaches)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 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