Use Obj {}to find the Duplicate Number

Tomlai
2 min readApr 2, 2021

--

Photo by Jon Tyson on Unsplash

Last time we used .Set() to solve this algorithm problem. This time we are using different approach. Let take a look for how to use object to set key and value, then looping through the array. It is really useful because it can also let us use this concept on different type of problem.

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:2

First of all, create a new empty object = {}, then we use a for loop to loops through individual element in the array and change them to the key of Obj.
Once we set the element in the array become Key of object , we can create a function to add the value of object each time when the key show up in the first for loops.
obj [nums[i]] = obj [nums[i]]+ 1 || 1
if the key of object does not exist in the new object, set its value to 1; if the key of object already exist in the new object, add 1 more to its value.

Now in the second step, for in loop we have key and value to loop through. we set an if statement. if(obj[num]>1), if the value is greater than 1, then return the key. Because if the value is greater than 1, that mean the key show up more than one time in the array.

Overall, set the element into object may sounds confusing at first but once we get used to it, this is a great way to find out unique, duplicate or even more complex element of array problem. Nothing wrong to learn more handy skill into your skill set, it will only help whenever you need it.

--

--