DEV Community

DR
DR

Posted on

2

#217: Contains Duplicate

Honestly, this was the easiest problem I've come across so far on LeetCode. The directives were as follows:

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.

Immediately I started thinking about using one of JS's built in data types, specifically Set(). Why? Because a set doesn't contain duplicates, so instead of iterating the traditional way, we can just convert the array to a set, back to an array, and compare the lengths to see if there were any duplicates that the set eliminated.

Let's take a look at first converting the array to a set.

function containsDuplicate(nums) {
  return new Set(nums);
}
Enter fullscreen mode Exit fullscreen mode

Nice - remember that we need to use the new keyword and not just Set(). Now, the value stored in that is the list with all duplicates eliminated. Let's convert that back to an array so we can compare more easily.

function containsDuplicate(nums) {
  return [...new Set(nums)];
}
Enter fullscreen mode Exit fullscreen mode

I'm using the spread operator because it looks cleaner, but you could also use Array.from() or any other method. Now, let's look at the final step - comparing the lengths.

why compare the lengths? It's simple - because if there were any duplicates, the set will have deleted them from our new array so the lengths will be different. Therefore, we'll return if they aren't different so we correctly handle the booleans (true if there were duplicates, false if there weren't).

function containsDuplicate(nums) {
  return [...new Set(nums)].length != nums.length;
}
Enter fullscreen mode Exit fullscreen mode

So there you go. An elegant one-liner that does the job pretty efficiently.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay