Skip to main content

Contains Duplicate

KANISHKA GUPTA
EditReport

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

#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;
}
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 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.