Contains Duplicate LeetCode Solution

Here, We see Contains Duplicate Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Contains Duplicate LeetCode Solution

Contains Duplicate LeetCode Solution

Problem Statement

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:
Input: nums = [1,2,3,1]
Output: true

Example 2:
Input: nums = [1,2,3,4]
Output: false

Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Contains Duplicate Leetcode Solution C++

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        if (nums.empty()) { return false; }
        unordered_map<int,int> mp;
        for (int i : nums) {
            if (++mp[i] > 1) {
                return true;
            }
        }
        return false;
    }
};
Code language: C++ (cpp)

Contains Duplicate Leetcode Solution Java

class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums==null || nums.length==0)
            return false;
        HashSet<Integer> hset = new HashSet<Integer>();
        for(int idx: nums){
            if(!hset.add(idx)){
                return true;
            }
        }
        return false;
    }
}
Code language: Java (java)

Contains Duplicate Leetcode Solution JavaScript

var containsDuplicate = function(nums) {
    const s = new Set(nums);
return s.size !== nums.length
};
Code language: JavaScript (javascript)

Contains Duplicate Leetcode Python

class Solution(object):
    def containsDuplicate(self, nums):
        return len(nums) != len(set(nums))
Code language: Python (python)
Scroll to Top