VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-number-pairs-xy-yx/

⇱ Number of pairs (x, y) in an array such that x^y > y^x - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of pairs (x, y) in an array such that x^y > y^x

Last Updated : 15 May, 2026

Given two positive integer arrays a[] and b[], find the number of pairs such that xy > yx(raised to power of) where is from a[] and is from b[].

Examples:

Input: a[] = [2, 1, 6], b[] = [1, 5]
Output: 3
Explanation: The pairs which follow xy > yx are: 21 > 12,  25 > 52 and 61 > 16

Input: a[] = [2 3 4 5], b[] = [1 2 3]
Output: 5
Explanation: The pairs which follow xy > yx are: 21 > 12 , 31 > 13 , 32 > 23 , 41 > 14 , 51 > 15.

[Naive Approach] Iterating over all pairs - O(n^2) Time and O(1) Space:

Iterate over all the possible pairs(x, y) in a[] and b[] and for each pair (x, y) check if x ^ y > y ^ x. If yes, then increment the count.


Output
3

[Expected Approach] Using Binary Search - O(n log n + m log n) Time and O(1) Space: 

To optimize the solution, array b is first sorted. Sorting helps us use binary search to quickly find how many numbers in b are greater than a given value.

For most cases, if y > x, then x^y > y^x
So for each value aval in array a[], we mainly count elements in b[] that are greater than aval. However, some values do not follow this rule.

Special values are: 0, 1, 2, 3, and 4
Their frequencies are stored separately in array cnt for fast access.

Case 1: aval == 0: No valid pair exists because: 0^y < y^0, So answer is 0.
Case 2: aval == 1: Only pair with 0 is valid because: 1^0 > 0^1, So add count of 0.
Case 3: aval > 1:: Use binary search to count all elements in b[] greater than aval and add count of 0 and 1 because they always form valid pairs.
Special Cases: When aval = 2: Pairs with 3 and 4 are not valid because: 2^3 < 3^2, 2^4 = 4^2 So subtract count of 3 and 4.
When aval = 3 Pair (3,2) is valid because: 3^2 > 2^3 , So add count of 2.

Finally, add all valid counts obtained for every element of a[]. The final sum gives the total number of valid pairs.


Output
3


Comment
Article Tags:
Article Tags: