19 March 2024
Easy
217. Contains Duplicate
Link: https://leetcode.com/problems/contains-duplicate
Description: We need to find if array of numbers have duplicate or not.
First solution:
Create new set (set is collection of unique values) from array and compare its size with array length.
var containsDuplicate = function (nums) {
return new Set(nums).size !== nums.length
}
Second solution:
Create object and count how many times each number appears in array. Then check if any number appears more than once.
var containsDuplicate = function (nums) {
const obj = {}
for (const n of nums) {
if (obj[n]) {
obj[n] += 1
continue
}
obj[n] = 1
}
return Object.values(obj).some((n) => n > 1)
}
First solution is faster than second one.