#217: Contains Duplicate

jd2r

DR

Posted on January 9, 2023

#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.

πŸ’– πŸ’ͺ πŸ™… 🚩
jd2r
DR

Posted on January 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related