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(1based 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(N^{2})
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++

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