Count pairs of indices with a specific property in an Array – GeeksforGeeks

Given an array a[] of size n containing only non-negative integers, and an integer k, the task is to find the number of pairs of indices (i, j) such that i < j and k * a[i] ≤ a[j].

Examples:

Input: a[] = {3, 5, 2, 4}, n = 4, k = 2
Output: 6
Explanation: The pairs satisfying the condition are: (1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5)

Input: a[] = {2, 4, 1, 6, 3}, n = 5, k = 3
Output: 5
Explanation: The pairs satisfying the condition are: (1, 3), (1, 5), (2, 5), (3, 4), (3, 5)

Approach: This can be solved with the following idea:

Sort the array, and find the index of the element equal to or greater than k * a[i], then all the elements will satisfy the condition.

Steps involved in the implementation of code

  • Sort the array in non-decreasing order.
  • For each index, i starting from the second, use binary search to find the index j such that k * a[i] a[j] and j > i.
  • Add the number of indices found by binary search to the answer.
  • Return the final answer.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

  

int count_pairs(vector<int>& a, int k)

{

  

    

    sort(a.begin(), a.end());

    int n = a.size(), ans = 0;

  

    for (int i = 1; i < n; i++) {

  

        

        

        auto it = lower_bound(a.begin() + i + 1, a.end(),

                              k * a[i]);

  

        int j = it - a.begin();

  

        ans += j - i;

    }

    return ans;

}

  

int main()

{

  

    vector<int> a1 = { 1, 2, 3, 4, 5 };

    int k1 = 2;

  

    

    cout << count_pairs(a1, k1) << endl;

  

    return 0;

}

Time Complexity: O(n * log(n))
Auxilairy Space: O(1) 

 

Stay connected with us on social media platform for instant update click here to join our  Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here 

Read original article here

Denial of responsibility! FineRadar is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – abuse@fineradar.com. The content will be deleted within 24 hours.
arraycountfineradar updateFree Fire Redeem Codesgadget updateGeeksforGeeksindicesLatest tech newsPairspropertySpecificTech Headlinestech newsTech News UpdatesTechnologyTechnology News
Comments (0)
Add Comment