HackerRank – Sock Merchant

Share on facebook
Share on google
Share on twitter
Share on linkedin

Quick and dirty, running on a loop, counting, gathering and calculating the socks ๐Ÿ˜€

Exercise Description

John’s clothing store has a pile of n loose socks where each sock i is labeled with an integer, C(i), denoting its color. He wants to sell as many socks as possible, but his customers will only buy them in matching pairs. Two socks, i and j, are a single matching pair if C(i)=C(j).

Given n and the color of each sock, how many pairs of socks can John sell?

function getSocksPairs(socks) {  
    var counters = {};
    var pairs = 0;

    for (var i=0 ; i<socks.length ; i++) {
        var cur = socks[i];

        if (cur in counters) {
        } else {
            counters[cur] = 1;

    for (var counterKey in counters) {
        pairs += Math.floor(counters[counterKey]/2);
    return pairs;