Finding peculiar pairs in array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of Integers, arr, as the first and the only argument.

Our function should count the occurrence of all such index pairs (i, j) that satisfy the following conditions −

  • I < j, and

  • arr[i] > 2 * arr[j]

For example, if the input to the function is −

const input = [2, 4, 3, 5, 1];

Then the output should be −

const output = 3;

Output Explanation:

Because the three desired pairs are −

[4, 1], [3, 1] and [5, 1]

Example

The code for this will be −

 Live Demo

const arr = [2, 4, 3, 5, 1];
const peculiarPairs = (arr = []) => {
   let count = 0;
   let copy = arr.slice().sort((a,b)=> a - b);
   let bit = new Array(arr.length+1).fill(0);
   for (const num of arr){
      count += search(bit, indexed(copy, 2*num+1));
      bit = insert(bit, indexed(copy, num));
   };
   return count;
};
const search = (bit, i) => {
   let sum = 0;
   while (i < bit.length){
      sum += bit[i];
      i += i & -i;
   }
   return sum;
}
const insert = (bit, i) => {
   while (i > 0){
      bit[i] += 1;
      i -= i & -i;
   }
   return bit;
}
const indexed = (arr, val) => {
   let l = 0, r = arr.length-1, m = 0;
   while (l <= r) {
      m = l + ((r-l) >> 1);
      if (arr[m] >= val){
         r = m-1;
      }else{
         l = m+1;
      }
   }
   return l+1;
}
console.log(peculiarPairs(arr));

Code Explanation

We have here used a Binary Indexed Tree (BIT) −

Binary Indexed Tree or BIT is represented as an array. Let the array be BITree[]. Each node of the Binary Indexed Tree stores the sum of some elements of the input array. The size of the Binary Indexed Tree is equal to the size of the input array.

Output

And the output in the console will be −

3

Updated on: 04-Mar-2021

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements