Member-only story
Coding Interview Prep— Contains Duplicate with 4 Solutions
1 min readJul 13, 2024
Prompt
Solution 1 — Brute Force using nested for loops
/*
Brute Force method
Time: O(n^2)
Space: O(1)
*/
var containsDuplicate_nestedForLoops = function(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;
}
Solution 2 — Sorting Method and check the adjacent element
Sort the array and check if the next element is a duplicate of the current element.
/*
Sorting Method: compare 2 neighbors
Time: O(nlogn) from sorting
Space: O(1)
*/
var containsDuplicate = function(nums){
const sort = nums.sort((a,b)=>a-b);
for (let i=0; i<sort.length; i++){
if (i+1 < sort.length){
if (sort[i]==sort[i+1]){
return true;
}
}
}
return false;
}
Solution 3 — Hashing Method
/*
Hashing Method
Time Complexity: O(n)
Space Complexity: O(n)
*/
var containsDuplicate = function(nums) {
let obj = {};
for (let i=0; i<nums.length; i++){
let num = nums[i];
if (obj[num]){
return true;
} else {
obj[num] = true;
}
}
return false;
}
Solution 4 — Compare Lengths of Array vs. Set
/*
Compare length of array vs. set. The set will remove the unique elements.
Time Complexity: O(n) to create the set
Space Complexity: O(n)
*/
var containsDuplicatex = function(nums) {
return nums.length !== new Set(nums).size;
};