Problem 217

Abstract / Summary

Determine if a list of numbers has any repeated elements.

Note

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

C++ 0217.cpp

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return unique(nums.begin(), nums.end()) != nums.end();
    }
};
7 lines | 192 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (10+ 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 determines whether a vector of integers contains any duplicate values. It follows a two-phase approach: first it orders the elements, then it checks for repetition by collapsing adjacent equal entries. The result is a boolean indicating the presence of at least one duplicate.

Sorting Phase

sort(nums.begin(), nums.end());

The algorithm begins by invoking the standard library sort function on the entire range of the input vector. This operation rearranges the elements into non-decreasing order. By sorting in place, the code avoids allocating an auxiliary container, thereby keeping the memory footprint minimal. The use of the highly tuned introsort implementation in the standard library ensures that the sorting step adapts to the characteristics of the data, providing efficient handling for partially ordered inputs as well as random distributions.

Duplicate Detection Phase

return unique(nums.begin(), nums.end()) != nums.end();

After sorting, the unique algorithm is applied to the same range. unique removes consecutive duplicate elements by moving the distinct values toward the front of the range and returns an iterator to the new logical end. Because the vector is already sorted, any duplicates will be positioned next to each other, guaranteeing that unique will collapse all repetitions in a single linear pass. The comparison of the iterator returned by unique with nums.end() reveals whether any elements were eliminated: if the iterator points before the original end, at least one duplicate existed; otherwise, the vector was already composed of unique values.

Edge Cases Handled

When the input vector is empty, the sort call operates on an empty range, which is a no-op, and unique likewise returns the original end iterator. The comparison therefore yields false, correctly indicating that no duplicates are present. For a single-element vector, sorting again has no effect, and unique returns the end iterator unchanged, leading to a false result as expected. In the scenario where all elements are identical, sorting leaves the vector unchanged, while unique collapses the entire range to a single element and returns an iterator pointing to the second position. The inequality with nums.end() evaluates to true, correctly reporting the presence of duplicates. Conversely, when every element is distinct, sorting arranges them in order but does not create adjacent equals; unique returns the original end iterator, and the function returns false. The algorithm also gracefully handles negative numbers, large integer values, and mixtures of positive and negative values because the comparison operators used by sort and unique are defined for the full range of int.

Performance Optimizations Observed

The implementation leverages in-place operations, eliminating the need for auxiliary data structures such as hash tables or additional vectors. By sorting first, the code transforms the duplicate detection problem into a linear scan, allowing unique to run in O(n) time after the O(n log n) sorting step. The standard library’s sort employs introsort, which combines quicksort, heapsort, and insertion sort to adapt to different input patterns, reducing the likelihood of pathological performance. The subsequent call to unique works directly on the sorted memory layout, benefiting from cache locality because it accesses elements sequentially. The final comparison is a simple pointer check, adding negligible overhead. Overall, the design achieves a balance between time efficiency and low memory consumption while relying on well-optimized library primitives.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box filled with numbered blocks. Sometimes, you might accidentally put two blocks with the same number into the box.

To find out if there are any duplicate blocks, the first step is to line them up in a perfect row from the smallest number to the biggest number. Putting them in order makes it very easy to compare neighbors.

Once the blocks are in a nice line, you walk down the row and look at each neighbor next to each other. If two neighbors are wearing the same number, you know that you found a duplicate. If you finish walking down the whole line and every neighbor is different, then every block is unique.

This code simply organizes all the blocks into that neat line and checks each neighbor to see if they match.

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.54 | σ = 1.84

Complexity Analysis

Time: loglinear
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 C# C Rust JS Go TS PHP
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C TS
MacJim C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C, TypeScript
MacJim C++
martianoff Scala
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
64 links | 44 authors | 14 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video '217. Contains Duplicate Leetcode Problem | Solution with Explanation | DSA Problem Series'
Coding Blocks 5 mins
217. Contains Duplicate Leetcode Problem | Solution with Explanation | DSA Problem Series
YouTube video 'Leetcode | 217. Contains Duplicate | Easy | Java Solution'
Developer Docs 4 mins
Leetcode | 217. Contains Duplicate | Easy | Java Solution
YouTube video 'Contains Duplicate - LeetCode 217 - Python'
Deepti Talesra 10 mins
Contains Duplicate - LeetCode 217 - Python
YouTube video '217. Contains Duplicate | JavaScript | Set | O(n) Time Complexity | LeetCode Data Structures'
LeetCodeWithMonu 7 mins
217. Contains Duplicate | JavaScript | Set | O(n) Time Complexity | LeetCode Data Structures
YouTube video '217. Contains Duplicate | JavaScript | Brute Force | HashSet | O(n) | Blind 75 LeetCode Problem'
LeetCodeWithMonu 11 mins
217. Contains Duplicate | JavaScript | Brute Force | HashSet | O(n) | Blind 75 LeetCode Problem
YouTube video 'Contains Duplicate | LeetCode 217 | Theory + Python code'
Sai Anish Malla 7 mins
Contains Duplicate | LeetCode 217 | Theory + Python code
YouTube video '217  Contains Duplicate - LeetCode JavaScript'
Becoming A Better Dev (with David) 6 mins
217 Contains Duplicate - LeetCode JavaScript
YouTube video 'Contains Duplicate | LeetCode 217 | Java'
Tech Tutor 5 mins
Contains Duplicate | LeetCode 217 | Java
YouTube video '2. Leetcode 217. Contains Duplicate : JAVA'
Web Fusion with Bharadwaj 12 mins
2. Leetcode 217. Contains Duplicate : JAVA
YouTube video 'Contains Duplicate - LeetCode 217 - Coding Interview Questions'
One Code Man 3 mins
Contains Duplicate - LeetCode 217 - Coding Interview Questions
YouTube video '217 Contains Duplicate LeetCode - JavaScript (Pair Programming)'
Becoming A Better Dev (with David) 40 mins
217 Contains Duplicate LeetCode - JavaScript (Pair Programming)
YouTube video '1. Leetcode 217. Contains Duplicate : Javascript'
Web Fusion with Bharadwaj 11 mins
1. Leetcode 217. Contains Duplicate : Javascript
YouTube video '1. Leetcode 217. Contains Duplicate : JAVA'
Web Fusion with Bharadwaj 14 mins
1. Leetcode 217. Contains Duplicate : JAVA
YouTube video 'LeetCode 217: Contains Duplicate | C# Solution | HashSet vs Sorting Approach |'
Code Scribbler 4 mins
LeetCode 217: Contains Duplicate | C# Solution | HashSet vs Sorting Approach |
YouTube video 'Contains Duplicate - Google Interview Questions - LeetCode 217 Solution - C++'
nexTRIE 4 mins
Contains Duplicate - Google Interview Questions - LeetCode 217 Solution - C++
YouTube video '217. Contains Duplicate | Leetcode | Arrays |  Fundamentals'
Coding with Tamilarasan 8 mins
217. Contains Duplicate | Leetcode | Arrays | Fundamentals
YouTube video 'Leetcode 217 - Contains Duplicate (Java, Solution Explained)'
LC Bear 4 mins
Leetcode 217 - Contains Duplicate (Java, Solution Explained)
YouTube video 'Leetcode Solution - 217 Contains Duplicate'
John Leonardo 6 mins
Leetcode Solution - 217 Contains Duplicate
YouTube video '217. Contains Duplicate (Leetcode Easy)'
Programming Live with Larry 3 mins
217. Contains Duplicate (Leetcode Easy)
YouTube video 'Leetcode 217 🔥 Contains Duplicate | HashSet + Sorting Approach | Java DSA Handwritten'
Study Placement 6 mins
Leetcode 217 🔥 Contains Duplicate | HashSet + Sorting Approach | Java DSA Handwritten
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 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