Javascript Sock Merchant Challenge – Solution 1

READ FIRST: As noted in the comments and on the twitter thread, the solution in part 1 is not necessarily a performant one. A second solution will be shared in the second part and is usually more optimized for these types of challenges.

A quick preface

Truth be told I’m not a fan at all of algorithm code challenges. That might be surprising to hear from someone who’s putting up a tutorial on how to solve one, and who on top of it has made a mission of ‘fixing the Javascript Interview process’. The reality is that, if you are to get hired anywhere as a Javascript developer, it would be hard and almost impossible in the current state to bypass these types of challenges.
Hacker Rank is the perfect playground to get your feet wet and build up your algorithms-building skills. The Sock Merchant challenge is one of the fun ones. It might be a bit scary if you have never been presented to problems this way, but I can guarantee you that you are subconsciously solving way more complex ones every day.

The challenge

Hacker Rank Sock Merchant Page
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

The code

function sortAndCount( n, arr ) {
let sorted = arr.sort( (a,b) => a – b);
let pairs = 0;

for (let i = 0; i < n - 1; i++) { if ( sorted[i] === sorted[i + 1]) { pairs++; i += 1; } } return pairs; } Video Transcript So one way to solve for the sock merchant challenge is to sort the array, compare each item side by side to find a pair and total the number of pairs we find So our first step, we will create a variable to hold the sorted array and use the built-in sort method the sort method can take a compare function as an argument. The passed-in compare function will ensure that items are sorted in ascending order Next, we create a pairs variable which will hold the final count, we default it to 0 At this point, this would be the expected output from sorted if we were to pass in our socks array Next, we set up a for loop. We naturally start at index 0 but since we are going to compare items side by side we make a full stop at last index Now we can compare each item of the array with its direct sibling to Find a pair We increment the pair's value if we find a match. We also increment i By one to skip the next item since we have already checked it If the two items do not match the normal loop cycle will continue We have now sorted and compared side by side let’s run our solution This is a good first solution suitable for small arrays but can surely be improved upon. Let me know about your take on it in the comments

Link: https://dev.to/adyngom/javascript-sock-merchant-challenge-solution-1-4knh