Hackerrank Sock Merchant (C++)

C++ :

int sockMerchant(int n, vector<int> ar) {
    int noOfSockPairs = 0;

    //sorting the vector of socks
    sort(ar.begin(), ar.end());

    for(int i = 0; i < n - 1; i+=2){
        if(ar[i] == ar[i + 1]){
            i -= 1;

    return noOfSockPairs;


Sort the socks with sort(). (Try saying this 10 times quickly.) The for loop finds pairs of socks with the same numbers, and add 1 to noOfSockPairs each time a pair is found (eg. 10, 10). However, if there is an orphan sock, the else statement takes care of it by skipping over it (i – 1), since the for loop jumps over 2 numbers in each round (due to comparing 2 socks each round).

You may also like...

Leave a Reply

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