Contains Duplicate LeetCode Solution

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

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 C++ Solution ->

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 Java Solution ->

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 JavaScript Solution ->

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

Contains Duplicate Python Solution ->

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

Leave a Comment

Your email address will not be published. Required fields are marked *