Skip to content
Advertisement

Sock Merchant problem in javascript using splice not working

My following solution worked for 6 test cases out of 9 test cases and i couldn’t wrap my head around on why is it not working for the following test case. Note: I used splice instead of the sorting first methodology. Thanks in advance.

The problem: https://www.hackerrank.com/challenges/sock-merchant/problem

function sockMerchant(n, ar) {
    var i=0,j=1;
    var count = 0;
        while(i<=ar.length-1 && ar.length>1){

            if (ar[i]==ar[j]){
                ar.splice(i,1);
                ar.splice(j,1);
                count++;
                i=0;
                j=i+1;
            }
            else{
            if(j>=ar.length-1){
                i++;
                j=i+1;
            }else{
                j++;
            }
            }
        }
return count;
}

Successful test case: 10 20 20 10 10 30 50 10 20

Output: 3

Failed test case: 4 5 5 5 6 6 4 1 4 4 3 6 6 3 6 1 4 5 5 5

Output(expected):9

Advertisement

Answer

Since your index ‘j’ is always larger than index ‘i’, you should not splice ‘i’ first. Removing the lower element will offset index of all following array elements.

Try change

ar.splice(i,1);
ar.splice(j,1);

to

ar.splice(j,1); // remove higher element first
ar.splice(i,1);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement