Sales by Match with using Obj{}

Tomlai
2 min readApr 23, 2021

--

Photo by billow926 on Unsplash

Yes our algorithm problem this time from HackerRank is trying to solve something that sales by match. It is using socks as example and let take a look into this.

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

example

n = 7
ar = [1,2,1,2,1,3,2]
There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

return

int: the number of pairs

We are using object in this case, may be not the best way to do it but i think it is simple to understand it. First set the empty obj and count as 0, now we loop through the array with If statement ( if the object of key exist in the new empty object ?), if yes add one to the count and then keep looping, if not then set it equal to 1. When the array keep loop through it will hit the element that already exist (in the new object we create) and we will add it to count and remove it. Once the looping to the end, we can just return our count as our answer.

--

--