C++ 0217.cpp
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
return unique(nums.begin(), nums.end()) != nums.end();
}
};
Difficulty
and has an acceptance rate of about 65% (10+ 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 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.
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.
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 | 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++ |
Videos
Similar Problems
- problem 219: Contains Duplicate II
- problem 2357: Make Array Zero by Subtracting Equal Amounts
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
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