Using Set Length with an Easy Level LeetCode: Contains Duplicate

In this series, I will explain my thought process of figuring out one way to solve a particular LeetCode problem and then provide the JavaScript code.

217. Contains Duplicate

In this problem, the objective is to return true if any value is presented in the array at least twice and to return false if each value is distinct.

An example test case:

We will create a set of the original array. Then, we’ll make a new array and populate it with the values of the set by using the spread operator.

Since a set will only include unique values (you can imagine it as if the duplicates were getting tossed out), we can just compare the length of the new array with the argument. If there were any duplicates, the length wouldn’t be the same.

Of course, there are many ways to solve a problem, so feel free to share your thoughts in the comments below!

EDITED 11/15/2021:

I realize that this doesn’t actually solve the problem directly, so here is another way to solve the problem:

As mentioned in this article, we can use a dictionary to keep track of the numbers and the tally for each. Then, if we are able to find a number that has a tally of anything over 1, we’ll return true.

Ready for a Medium level LeetCode problem?

☕️If you enjoyed this article, please consider tipping here:



Software Engineer📍Tokyo. ☕️

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store