How I Solved Hacker Rank Challenge, Sales by Match

Danielle Torres
3 min readApr 19, 2021

Hi Everyone,

Today I will be reviewing how I solved the Sales by Match using JavaScript, level: easy.

The Objective: 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.

When I first encountered this challenge. I was completely intimidated. I never before solved any algorithms and I had no clue how to begin to solve it. After many other algorithm failures it began to click to look for patterns. To think more logically.

I decided to sort the array. This way it would be easier to determine if the integer is a pair. Below are the variables I created.

let i = 0;let count = 1; 
//I use this variable to count the socks. I set it to one as their always be at least one sock.
let pair = 0;
//If the count can be factored by two its a pair
let sortedArr = ar.sort();
//Used to store my sorted array
let num = 0;
//I use this variable to store the integer I'm evaluating

I use a for loop to iterate through the sorted array. If the integer stored in variable num equals the integer being evaluated in the sorted array then it will increment the count by 1.

If the count is a factor of two then it will increment the pair variable by 1 as the sock is a pair, if the integer stored in num is different than the integer being evaluated in the sorted array then I want to store this new number in the num variable and reset the count to 1.

for instance: [10 =>1, 10 =>2[pair], 10 => 3, 10 => 4[pair], 20 =>1[reset], 20=>2[pair], 30=>1[reset], 50=>1[reset];

After the loop is complete it will return the pair variable. In the above case, 3. Below is the complete, function.

// Complete the sockMerchant function below.function sockMerchant(n, ar) {let i = 0;
let count = 1;
let pair = 0;
let sortedArr = ar.sort();
let num = 0;
for (i=0; i < sortedArr.length; i++) {if (num === sortedArr[i]) {
count += 1
if ((count % 2) === 0) {
pair += 1;
};
} else if (num !== sortedArr[i]) {
num = sortedArr[i];
count = 1;};
};
return pair;
}
It passed! Please let me know if this helps you or if you enjoy the content. Until next time!

--

--

Danielle Torres

Highly organized & motivated Software Engineer with an application analyst/data analyst background.