(919) 964-9842
(919) 964-9842

Hackerrank in PHP: Sock Merchant

I am terrible at coding tests, and trying my best to get better at them. This was technically an "easy" one and it took me 45 minutes! But I got it done after much struggling on the struggle bus.

Long story short, John is working at a sock store and is desperately trying to determine how many pairs of socks he has based on the total number of socks he has as well as a convenient array of the sock types to compare against. So how can we help John? Develop a quick solution to print out exactly how many socks he has.

function sockMerchant($n, $ar) {
  $pairs = 0;
  for($i = 0; $i < $n; $i++) {
    if(isset($ar[$i + 1]) && $ar[$i] == $ar[$i + 1]) {
  return $pairs;

But Christina, what does any of that mean? First thing first, we need a clean variable to count with, so we have $pairs set to zero. Then, we're going to sort the array ascending based on type (which in our case, is just numerically thank goodness). Why do we sort the array? This way all the matches are lined up next to each other and we can easily see where they are. Next piece is to now go through our handy number of socks we have, or in this case, $n. Considering the array is not associative (or using strings for keys), we can use the numeric keys to check one next to the other.

So check is the current array item and the one next to it have the same value? If yes, we want to increase our pair count, and most importantly (where I got tripped up), you also need to increase the loop count, because we already checked the next item and determined its a pair. If we don't increase the loop count, it will consider the next item as a unique sock, and then inflate our pairs number.

I hope this makes sense! I'll be posting some more as I go along.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *