No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x

Given an array and two numbers x and k. Find the number of different ordered pairs of indexes (i, j) such that a[j] >= a[i] and there are exactly k integers num such that num is divisible by x and num is in range a[i]-a[j].
Examples:Â
Input : arr[] = {1, 3, 5, 7}
x = 2, k = 1
Output : 3
Explanation: The pairs (1, 3), (3, 5) and (5, 7)
have k (which is 1) integers i.e., 2, 4, 6
respectively for every pair in between them.
Input : arr[] = {5, 3, 1, 7}
x = 2, k = 0
Output : 4
Explanation: The pairs with indexes (1, 1), (2, 2),
(3, 3), (4, 4) have k = 0 integers that are
divisible by 2 in between them.
A naive approach is to traverse through all pairs possible and count the number of pairs that have k integers in between them which are divisible by x.Â
Time complexity: O(n^2), as we will be using nested loops for traversing n*n times.
An efficient approach is to sort the array and use binary search to find out the right and left boundaries of numbers(use lower_bound function inbuilt function to do it) which satisfy the condition and which do not. We have to sort the array as it is given every pair should be a[j] >= a[i] irrespective of value of i and j. After sorting we traverse through n elements, and find the number with whose multiplication with x gives a[i]-1, so that we can find k number by adding k to d = a[i]-1/x. So we binary search for the value (d+k)*x to get the multiple with which we can make a pair of a[i] as it will have exactly k integers in between a[i] and a[j]. In this way we get the left boundary for a[j] using binary search in O(log n), and for all other pairs possible with a[i], we need to find out the right-most boundary by searching the number equal to or greater than (d+k+1)*x where we will get k+1 multiples and we get the no of pairs as (right-left) boundary [index-wise]. Â
Implementation:
C++
// C++ program to calculate the number// pairs satisfying the condition#include <bits/stdc++.h>using namespace std;Â
// function to calculate the number of pairsint countPairs(int a[], int n, int x, int k){Â Â Â Â sort(a, a + n);Â Â Â Â
    // traverse through all elements    int ans = 0;    for (int i = 0; i < n; i++) {Â
        // current number's divisor        int d = (a[i] - 1) / x;Â
        // use binary search to find the element         // after k multiples of x        int it1 = lower_bound(a, a + n,                          max((d + k) * x, a[i])) - a;Â
        // use binary search to find the element        // after k+1 multiples of x so that we get         // the answer by subtracting        int it2 = lower_bound(a, a + n,                     max((d + k + 1) * x, a[i])) - a;Â
        // the difference of index will be the answer        ans += it2 - it1;    }    return ans;}Â
// driver code to check the above functionint main(){Â Â Â Â int a[] = { 1, 3, 5, 7 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â Â Â Â int x = 2, k = 1;Â
    // function call to get the number of pairs    cout << countPairs(a, n, x, k);    return 0;} |
Java
// Java program to calculate the number// pairs satisfying the conditionimport java.util.*; Â
class GFG{Â
// function to calculate the number of pairsstatic int countPairs(int a[], int n, int x, int k){Â Â Â Â Arrays.sort(a); Â
    // traverse through all elements    int ans = 0;    for (int i = 0; i < n; i++)     {Â
        // current number's divisor        int d = (a[i] - 1) / x;Â
        // use binary search to find the element         // after k multiples of x        int it1 = Arrays.binarySearch(a,                     Math.max((d + k) * x, a[i]));Â
        // use binary search to find the element        // after k+1 multiples of x so that we get         // the answer by subtracting        int it2 = Arrays.binarySearch(a,                    Math.max((d + k + 1) * x, a[i])) ;Â
        // the difference of index will be the answer        ans += it1 - it2;    }    return ans;}Â
// Driver code public static void main(String[] args){Â Â Â Â int []a = { 1, 3, 5, 7 };Â Â Â Â int n = a.length;Â Â Â Â int x = 2, k = 1;Â
    // function call to get the number of pairs    System.out.println(countPairs(a, n, x, k));}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program to calculate the number# pairs satisfying the conditionÂ
import bisectÂ
# function to calculate the number of pairsdef countPairs(a, n, x, k):Â Â Â Â a.sort()Â
    # traverse through all elements    ans = 0    for i in range(n):Â
        # current number's divisor        d = (a[i] - 1) // xÂ
        # use binary search to find the element        # after k multiples of x        it1 = bisect.bisect_left(a, max((d + k) * x, a[i]))Â
        # use binary search to find the element        # after k+1 multiples of x so that we get        # the answer by subtracting        it2 = bisect.bisect_left(a, max((d + k + 1) * x, a[i]))Â
        # the difference of index will be the answer        ans += it2 - it1Â
    return ansÂ
# Driver codeif __name__ == "__main__":Â Â Â Â a = [1, 3, 5, 7]Â Â Â Â n = len(a)Â Â Â Â x = 2Â Â Â Â k = 1Â
    # function call to get the number of pairs    print(countPairs(a, n, x, k))Â
# This code is contributed by# sanjeev2552 |
C#
// C# program to calculate the number // pairs satisfying the condition using System;Â
class GFG{Â Â Â Â Â // Function to calculate the number of pairsstatic int countPairs(int[] a, int n, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int x, int k){Â Â Â Â Array.Sort(a);Â Â Â Â
    // Traverse through all elements    int ans = 0;    for(int i = 0; i < n; i++)     {                 // Current number's divisor        int d = (a[i] - 1) / x;Â
        // Use binary search to find the element         // after k multiples of x        int a1 = Math.Max((d + k) * x, a[i]);        int it1 = Array.BinarySearch(a, a1);Â
        // Use binary search to find the element        // after k+1 multiples of x so that we get         // the answer by subtracting        int a2 = Math.Max((d + k + 1) * x, a[i]);        int it2 = Array.BinarySearch(a, a2);Â
        // The difference of index will        // be the answer        ans += Math.Abs(it2 - it1);    }    return ans;}Â
// Driver Codestatic void Main() {    int[] a = { 1, 3, 5, 7 };    int n = a.Length;    int x = 2, k = 1;         // Function call to get the number of pairs     Console.Write(countPairs(a, n, x, k));}}Â
// This code is contributed by SoumikMondal. |
Javascript
// Javascript program to calculate the number// pairs satisfying the conditionÂ
function lower_bound(arr, N, X){Â Â Â Â let mid;Â Â Â Â let low = 0;Â Â Â Â let high = N;Â Â Â Â while (low < high) {Â Â Â Â Â Â Â Â mid = low + (high - low) / 2;Â Â Â Â Â Â Â Â if (X <= arr[mid]) {Â Â Â Â Â Â Â Â Â Â Â Â high = mid;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â else {Â Â Â Â Â Â Â Â Â Â Â Â low = mid + 1;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â if (low < N && arr[low] < X) {Â Â Â Â Â Â Â Â low++;Â Â Â Â }Â Â Â Â return low;}Â
// function to calculate the number of pairsfunction countPairs(a, n, x, k){Â Â Â Â a.sort();Â
    // traverse through all elements    let ans = 0;    for (let i = 0; i < n; i++) {Â
        // current number's divisor        let d = (a[i] - 1) / x;Â
        // use binary search to find the element        // after k multiples of x        let it1 = lower_bound(a, n,                              Math.max((d + k) * x, a[i]));Â
        // use binary search to find the element        // after k+1 multiples of x so that we get        // the answer by subtracting        let it2 = lower_bound(            a, n, Math.max((d + k + 1) * x, a[i]));Â
        // the difference of index will be the answer        ans += it2 - it1;    }    return ans;}Â
// driver code to check the above functionlet a = [ 1, 3, 5, 7 ];let n = 4;let x = 2, k = 1;Â
// function call to get the number of pairsconsole.log(countPairs(a, n, x, k));Â
// This code is contributed by garg28harsh. |
3
Time Complexity: O(N*logN), as we are using sort function which will cost N*logN.
Auxiliary Space: O(1), as we are not using any extra space.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



