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]){
noOfSockPairs++;
}else{
i -= 1;
}
}
return noOfSockPairs;
}
Explanation:
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).