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.
By | 8 months ago
interviewjobsjavascriptnodekeralacareerskochitrivandrum
To solve this problem in JavaScript, you can use a similar approach as you would in Python. You can use a Set
to keep track of the elements you've seen. If you encounter an element that's already in the set, it means there's a duplicate, and you can return true
. If you go through the entire array without finding a duplicate, you return false
.
Here's a JavaScript function that implements this logic:
function containsDuplicate(nums) { let seen = new Set(); for (let num of nums) { if (seen.has(num)) { return true; } seen.add(num); } return false; }
You can use this function containsDuplicate
by passing an array of integers, and it will return true
if there's any duplicate or false
if all elements are distinct.