Last updated on January 29th, 2025 at 02:46 am
Here, we see a Contains Duplicate LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Array, Hash Table
Companies
Airbnb, Palantir, Yahoo
Level of Question
Easy
Contains Duplicate LeetCode Solution
Table of Contents
1. 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
2. Coding Pattern Used in Solution
The coding pattern used here is “Hashing for Duplicate Detection”, which is not listed in the provided patterns. This pattern leverages hash-based data structures (like unordered_map
, HashSet
, Set
) to efficiently check for duplicates.
3. Code Implementation in Different Languages
3.1 Contains Duplicate 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; } };
3.2 Contains Duplicate 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; } }
3.3 Contains Duplicate JavaScript
var containsDuplicate = function(nums) { const s = new Set(nums); return s.size !== nums.length };
3.4 Contains Duplicate Python
class Solution(object): def containsDuplicate(self, nums): return len(nums) != len(set(nums))
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n) | O(n) |
Java | O(n) | O(n) |
JavaScript | O(n) | O(n) |
Python | O(n) | O(n) |