Contains Duplicate
217. Contains Duplicate
Description:
You are given an array of integers, nums, which may contain both positive and negative numbers. Your task is to determine whether any value appears more than once in the array. If at least one duplicate exists, return true. Otherwise, return false.
Video Explanation

Example 1:
Input:
nums = [1, 2, 3, 1]
Output:
true (because 1 appears twice)
Explanation:
- The frequency of 1 is 2
- The frequency of 2 is 1
- The frequency of 3 is 1
- Since 1 appears twice, there is a duplicate, so the output is
true.
Example 2:
Input:
nums = [1, 2, 3, 4]
Output:
false (because all elements are distinct)
Explanation:
- All elements are unique and appear only once.
Solutions
- C++
- Java
- Python
- JavaScript
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
bool containsDuplicate(const vector<int>& nums) {
unordered_set<int> uniques;
for (int num : nums) {
// If the number is already in the set, it means it's a duplicate
if (uniques.find(num) != uniques.end()) {
return true;
}
// Add the number to the set
uniques.insert(num);
}
return false;
}
int main() {
vector<int> nums = {1, 2, 3, 1}; // Example input
if (containsDuplicate(nums)) {
cout << "Array contains duplicates." << endl;
} else {
cout << "Array does not contain duplicates." << endl;
}
return 0;
}
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
return true;
}
}
return false;
}
}
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))
var containsDuplicate = function(nums) {
const set = new Set();
for (const num of nums) {
if (set.has(num)) return true;
set.add(num);
}
return false;
};
Done with this topic? Mark it as complete to track your progress.
Related Practice Problems
Handpicked problems sharing similar algorithmic topic tags
Left and Right Sum Differences
The Left and Right Sum Differences problem on LeetCode involves finding the absolute difference between the sum of elements to the left and right of each index in an array.
Weighted Word Mapping
Solution to the Weighted Word Mapping problem across C++, JavaScript, Java, and Python with complexity analysis.
An Alternative Way
Solution for Codeforces 2241D: An Alternative Way, utilizing a prefix sum invariant approach.
💬 Discuss this page
Have a question or spot something confusing in "Contains Duplicate"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.