Depend of pairs such that A[i], i, A[j] and j are in rising order

0
4


Given an array A[] of N integers, the duty is to seek out the variety of pairs of indices (1 ≤ i, j ≤ N) within the array such that A[i] < i < A[j] < j.

Examples:

Enter: N = 8, A[] = {1, 1, 2, 3, 8, 2, 1, 4}
Output: 3
Rationalization: The pairs satisfying the given situation are {(2, 4), (2, 8), (3, 8)}. 
For the pair (2, 4): A[2] = 1(1-based indexing), A[4] = 3 and 1 < 2 < 3 < 4.
For the pair (2, 8): A[2] = 1, A[8] = 4 and 1 < 2 < 4 < 8.
For the pair (3, 8): A[3] = 2, A[8] = 4 and a pair of < 3 < 4 < 8.

Enter: N = 2, A[] = {1, 2}
Output: 0

 

Naive Method: A primary strategy to remedy the issue could be to traverse the array utilizing two nested loops and examine the situation for every attainable pair.

Time Complexity: O(N2)
Auxiliary House: O(1)

Environment friendly Method: The issue could be solved utilizing a grasping method and binary search

Given Situation is A[i] < i < A[j] < j. Lets break it into three separate circumstances:

The weather of array having A[i] ≥ i can’t fulfill the first and third situation and therefore won’t be the a part of any pair satisfying the given situation. For remainder of the weather (say legitimate parts) 1st and third circumstances are already glad. So, among the many legitimate parts, merely rely the variety of pairs (i, j) satisfying the 2nd situation i.e. i < A[j].

Observe the steps to unravel the issue:

  • Initialize a variable (say ans) with 0, to retailer the full variety of pairs and a vector (say v) to retailer the positions of legitimate parts.
  • Whereas iterating by the array, if a component is larger than or equal to its place, then skip the iteration, as that component would by no means be capable to type a pair satisfying the required circumstances.
  • Else, simply add the variety of positions lower than the present component to the reply (to fulfill the 2nd situation i < A[j]), which could be calculated by the decrease certain on vector v of positions.
  • Additionally, at finish of every iteration, insert the place of every legitimate component to the vector v.

Under is the implementation for the above method:

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int countPairs(int A[], int N)

{

    

    int ans = 0;

  

    

    

    vector<int> v;

  

    

    for (int i = 0; i < N; i++) {

  

        

        

        

        if (A[i] >= (i + 1)) {

            proceed;

        }

  

        

        

        

        ans += lower_bound(v.start(), v.finish(), A[i])

               - v.start();

  

        

        

        v.push_back(i + 1);

    }

  

    

    return ans;

}

  

int principal()

{

    int N = 8;

    int A[] = { 1, 1, 2, 3, 8, 2, 1, 4 };

    int reply = countPairs(A, N);

  

    

    cout << reply << endl;

    return 0;

}

Time Complexity: O(N * log(N))
Auxiliary House: O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here