

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Questions & Answers
- Finding special array - JavaScript
- Beginning and end pairs in array - JavaScript
- Finding upper elements in array in JavaScript
- Finding unlike number in an array - JavaScript
- Finding median index of array in JavaScript
- Finding a number of pairs from arrays with smallest sums in JavaScript
- Finding unique string in an array in JavaScript
- Finding the maximum in a nested array - JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Finding degree of subarray in an array JavaScript
- Finding matching pair from an array in JavaScript
- Finding confusing number within an array in JavaScript
- Finding the Largest Triple Product Array in JavaScript
- Finding Fibonacci sequence in an array using JavaScript
Advertisements