Sign in

Use .Set() to Find the Duplicate Number

Photo by Mark Fletcher-Brown on Unsplash

This is an algorithm problem I believe a lot of people have seen before. And I see many people using object and set for key and value to loop through the array and solve the problem. Today we can try on something a little different but also easy to approach the problem. Thank you, my friend Stephanie Segura share this smart idea with us.

Question-

Given an array of integers nums containing n+1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number,

Example1:
Inputs: num = [1,3,4,2,2]
Output: 2

Example 2:
Inputs: num = [3,1,3,4,2]
Output: 3

According our good old friend Mozilla Doc, the Set() constructor lets you create Set objects that store unique values of any type, whether primitive values or object references.
So we can always use this build-in function with .has() to check our array has this number or not, it is kind of similar like .filter().
First we set the variable newSet = new Set(), it will allow us to use later on in the for loop and If statement to check the condition.

The key part is let newSet to check if it doesn't have any of the numbers in nums, add it to newSet. else we can just return the remaining numbers in nums.