The question is asking us to return a boolean value if an array of integers contains any duplicate values. There are various ways we can solve this question, but when trying to solve any problem that has to do with uniqueness we should think about Sets. Sets are objects that contain a collection of values and those values have to be unique. For more information on
Sets() check out the resources section located on the bottom of this blog.
This is how our code should look like as of right now:
The next step is to iterate through each element inside of the
nums array and see if the current number inside the array exists in the set
newSet. We can use the for statement syntax, but I’ll be using the
for of statement syntax just to show the different ways of solving this question. Check out the resources section below for more info on
for of loops. If the current number on the array doesn’t exist in the set, then that number should be added in
newSet. If the current number does exist, then we return
true since that number already exists inside of
newSet. Outside of the
for of loop or once the loop is finished, I would recommend setting the default boolean value to
false. We would do this because if all of the logic inside the
for of loop isn’t met, that means that the array doesn’t contain any duplicates.
According to LeetCode, this solution is actually one of the best approaches, here are the results when submitting the solution on Leetcode:
Overall it’s pretty good, but we can always figure out ways in which we can improve our code. For instance, we can still create a Set for this problem, but we don’t really need to iterate over anything. For this next solution, we can just compare the size of the set (
newSet) and the length of the array (
nums). If they’re equal to each other then that means that there are no duplicates in the array and if the array length is bigger then there’s a duplicate. Remember that sets are objects that hold unique values! Here’s the solution:
Here we can see that on line 3 I created the set, but also passed in
numsas an argument. I’m doing this because the set (
newSet) needs to have values inside, otherwise we will be working with an empty set. Here’s what
newSet with the
nums array as an argument and the nums array alone look like when you use
As we can see, the array has 4 elements while the set has 3 values. Again this is because sets hold unique values, so in this case the set is not going to have the number 1 again.
Here are the results when submitting this solution on LeetCode:
I hope this blog was able to help out in any way! I’m open to hearing about more solutions that may work so please reach out! Check out the resources section below for more information on sets!