#code/question #code/javascript #code/dsa

217 Contains duplicate

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.

Input: nums = [1,2,3,1]
Output: true

Approach

Either solving by BF, looping through the whole array, by using a hashset or by comparing a Set's size to the array length.

Solution

const containsDuplicate = nums => {
	let hash = {}

	for (let num of nums){
		if (hash[num]) {
			return false
		} else {
			hash[num] = 1
		}
	}
	return true
}
    return new Set(nums).size !== nums.length

Gotcha

References

LC

DSA MOC
Map in JavaScript
Set in JavaScript