Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairs algorithm on HackerRank

Let me quickly explain the problem

originally from here: https://www.hackerrank.com/challenges/pairs

Sample input is:

5 2  
1 5 3 4 2

referencing the above input

first line:

N = 5, K = 2 

where N is the number of integers in the set, and K is the difference we are looking for

second line (as an array):

[1, 5, 3, 4, 2];

How many pairs in the array have a difference of K ?

sample answer: "There are 3 pairs of integers in the set with a difference of 2."

here is something I'm working on for this, but I am missing something :

function findDifference(k, nArr) {

    nArr.sort((a, b) => a - b);

var pairsWithDifferenceOfK = 0;

for (var i = 0; i < nArr.length; i++) {
    if (Math.abs((nArr[i] - ((nArr.length > (i + k)) ? nArr[(i + k)] : nArr[i]))) === k) {
       pairsWithDifferenceOfK++;
   };
}
   console.log(pairsWithDifferenceOfK);
}
var K = 2;
Arr = [1, 5, 3, 4, 2];
findDifference(K, Arr);

output:

3

This fails when given these inputs ( and I am curious as to why this fails on some inputs and not others):

10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 42804763 491595254 879792181 1069262793
like image 691
Alex Anderson Avatar asked Aug 02 '26 02:08

Alex Anderson


1 Answers

One way to solve this could be with recursion. In each iteration of function you can take first element and then compare it to rest of elements. So for example you you start with

var rest = arr.splice(1);

where rest is [5, 3, 4, 2] and you compare each element to 1 and then you pass rest to function where you compare [3, 4, 2] to 5 etc... Then you check on each element if difference is k and if it is you increment result. When arr parameter becomes empty array function will exit or return 1.

var K = 2;
var array = [1, 5, 3, 4, 2];

function findDifference(k, arr) {
  var r = 0;

  function inner(k, arr) {
    if (!arr.length) return 1;
    var rest = arr.splice(1);

    rest.forEach(function(e) {
      if (Math.abs(arr[0] - e) == k) r++;
    })

    inner(k, rest);
  }
  inner(k, arr);
  return r;
}

console.log(findDifference(K, array));
like image 72
Nenad Vracar Avatar answered Aug 03 '26 17:08

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!