Search code examples
c#.netalgorithmsearcharray-algorithms

Where is my mistake in solution of HackerRank - "Pairs" problem (rated medium)?


Given an array of integers and a target value, determine the number of pairs of array elements that have a difference equal to the target value.

Here is the link to the problem: https://www.hackerrank.com/challenges/pairs/problem

My algorithm is supposed to do the following:

  • Sort the array
  • compare 2 neighbour numbers (i, i+1): if difference between them is equal to given number k, increment result if the difference is less than given number, then compare i+1 with 0,...,i-1 elements to try to find possible pair among those. if the difference is grater than given number k, then increment i and do the same for the next pair.

I think the algorithm is correct & I cannot find mistake in the implementation. My code passes main test cases & passes 5/18 additional test cases. Please help me find my mistake.

Here's my code:

public static int pairs(int k, List<int> arr)
{
    arr.Sort();
    var result = 0;
    
    for (var i = 0; i < arr.Count - 1; ++i){
        var diff = arr[i + 1] - arr[i];
        if (diff > k) continue;
        else if (diff == k) ++result;
        else {
            result = CompareWithPreviousValues(arr, k, i + 1, result);
        }
    }
    
    return result;
}

private static int CompareWithPreviousValues(List<int> arr, int k, int indexOfElementToCompare, int result)    {
    var j = 2;
    for (var i = indexOfElementToCompare; i - j >= 0; --i){
        var diff = arr[i] - arr[i - j];
        if (diff < k) ++j;
        else if (diff == k){
            ++result;
            return result;
        }
        else return result;
    }
    
    return result;
}

Solution

  • before posting the question, I went through the code once again and found the mistake I made.. But since there's no discussion on this problem in stackoverflow and it maybe interesting for some folks to find mistake in code, I decided to post it anyway. And I've spend time on filling in the question :D

    So the mistake.. Of course it's a small one, but an unpleasing one. DISCLAMER For those of you, who would like to find the mistake, I recommend not reading further below as there's the fixed code :D

    The mistake is in the for loop of "CompareWithPreviousValues" method. After each iteration, for some reason i was decreased. I probably wrote that i mechanically, as most loops are working with "i"s. So here is the right version of the method:

    private static int CompareWithPreviousValues(List<int> arr, int k, int n, int result)    {
        var j = 2;
        for (var i = n; i - j >= 0; ++j){
            var diff = arr[i] - arr[i - j];
            if (diff < k) continue;
            else if (diff == k){
                ++result;
                return result;
            }
            else return result;
        }
        
        return result;
    }