Photo by Glenn Carstens-Peters on Unsplash
Contains Duplicate
Different Approaches to solve this problem in JavaScript
Before we dive into the solutions, let’s first understand the problem statement in detail.
“Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.”
Approach 1: Brute force
Compare each element of the array with all other elements and check if there are any duplicates.
If we find any duplicates, we return true; otherwise, we return false.
// ES6 Arrow Function
const containsDuplicate = nums => {
for(let i = 0; i < nums.length; i++) {
for(let j = i+1; j < nums.length; j++) {
if(nums[i] === nums[j]) return true;
}
}
return false;
}
Time Complexity: O(N²)
Space Complexity: O(1)
Approach 2: Sorting
Sort the given array and then check for duplicates.
If there are any duplicates, return true; Otherwise, return false;
// ES6 Arrow Function
const containsDuplicate2 = nums => {
nums.sort((a,b) => a-b);
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i - 1]) return true;
}
return false;
}
Time Complexity: O(N * log(N))
Space Complexity: O(1)
Approach 3: Sets
Create a new Set from the values of the input array.
Compare the length of the input array and the set.
No duplicates mean the length of the array and the set will be the same, return false.
Otherwise, return true.
// ES6 Arrow Function
const containsDuplicate = nums => {
const set = new Set(nums);
return set.size !== nums.length;
}
// Minified version
const containsDuplicate = nums => nums.length !== new Set(nums).size;
Time Complexity: O(N)
Space Complexity: O(N)
Approach 4: Maps
Use a hash table to keep track of the elements in the array.
Iterate over each element of the array and check if it already exists in the hash table.
If the element exists in the hash table, we return true; otherwise, we add the element to the hash table and continue iterating.
const containsDuplicate5 = nums => {
let map = new Map();
for(let i of nums) {
if(map.has(i)) return true;
map.set(i);
}
return false;
}
Time Complexity: O(N)
Space Complexity: O(N)
Note 1: Approach 4 can also be implemented using a Set. Therefore, the choice of approach depends on your preference.
Note 2: When solving this problem, using a hash table is a better approach compared to comparing the length of the original input array and the size of a Set. The main advantage of a hash table is its ability to quickly detect results while using a Set requires adding all elements before comparing its size.
I hope this article has provided you with valuable insights and helped you better understand the different approaches to solve this problem. Happy coding!
Problem - Leetcode 217