Number of pairs | Practice | GeeksforGeeks

Given two arrays X and Y of positive integers, find the number of pairs such that xy > yx (raised to power of) where x is an element from X and y is an element from Y.

Example 1:
Input: 
M = 3, X[] = [2 1 6] 
N = 2, Y[] = [1 5]
Output: 3
Explanation: 
The pairs which follow xy > yx are 
as such: 21 > 12,  25 > 52 and 61 > 16 .
Example 2:
Input: 
M = 4, X[] = [2 3 4 5]
N = 3, Y[] = [1 2 3]
Output: 5
Explanation: 
The pairs for the given input are 
21 > 12 , 31 > 13 , 32 > 23 , 41 > 14 , 
51 > 15 .

Your Task:
This is a function problem. You only need to complete the function countPairs() that takes X, Y, M, N as parameters and returns the total number of pairs.

Expected Time Complexity: O((N + M)log(N)).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ M, N ≤ 105
1 ≤ X[i], Y[i] ≤ 103
0
lindan1232 days ago
long long Solve(int val,int Y[],int freq[],int M, int N)   {       long long int pos = 0;       long long int res= 0;       if(val==0)       {           return 0;       }       if(val==1)       {           return freq[0];       }              pos = upper_bound(Y,Y+N,val)-Y;              res = res + (N - pos) + freq[0]+freq[1];              if(val==2)       {           res = res - (freq[3] + freq[4]);       }       if(val==3)       {           res = res + freq[2];       }       return res;    }   long long countPairs(int X[], int Y[], int M, int N)   {       int freq[5] = {0};              long long int count = 0;              for(int i=0;i<N;i++)       {           if(Y[i]<5)           {               freq[Y[i]]++;           }       }              sort(Y,Y+N);              for(int i=0;i<M;i++)       {           count = count + Solve(X[i],Y,freq,M,N);       }       return count;   }
 
Time Taken : 1.0sec
Cpp
-1
chandrikaamalakanti20033 weeks ago
can someone please tell me how to reduce the time complexity of my code?
def countPairs(self,a,b,M,N):
        count=0
        for i in range(M):
            for j in range(N):
                if(a[i]**b[j]>b[j]**a[i]):
                    count+=1
        return count

+2
abhijeet194031 month ago
A simple approach with keeping in mind the exceptions
The exceptions here are based on observations
 
Code in C++
 
long long countPairs(int X[], int Y[], int M, int N)   {      long long count = 0;      sort(Y,Y+N);      int count1=0,count2=0,count3=0,count4=0; //taking count of 1,2,3,4's occurances      for(int i=0;i<N;i++)      {          if(Y[i]>4)          break;
          if(Y[i]==1)          count1++;          else if(Y[i]==2)          count2++;          else if(Y[i]==3)          count3++;          else if(Y[i]==4)          count4++;      }      for(int i=0;i<M;i++) // Now handle the exceptions       {          if(X[i]==0) // handling exceptions          continue;          else if(X[i]==1) // handling exceptions          {             for(int j=0;j<N;j++)             {                 if(Y[j]==0)                 count++;                 else                 break;             }          }          else          {              int j = upper_bound(Y,Y+N,X[i])-Y;  // it gives the index of element just grater than X[i] or N if no such element is not present
              if(j!=N)              count += N-j;
              if(X[i]==2)  // handling exceptions              count = count - count3 - count4;
              if(X[i]==3)// handling exceptions              count = count + count2;
              count += count1; // handling exceptions          }      }      return count;   }
upvote if you likes the code
0
mohlebzo12 months ago
JS Solution:
class Solution {    //Function to count number of pairs such that x^y is greater than y^x.    countPairs(X, Y, M, N)   {       //your code here       let tempInt = 0;       X.map(elementX => Y.map(elementY => Math.pow(elementX, elementY) > Math.pow(elementY, elementX) ? tempInt++ : tempInt));       return tempInt;   }}
0
vandit11022 months ago
//Showing Tle I don't know why??
//Any suggestions??

 bool check(int x,int y)
   {
       return pow(x,y)>pow(y,x);
   }
   long long countPairs(int X[], int Y[], int M, int N)
   {
      //Your code here
      
      sort(Y,Y+N);
      long long i=M-1;
      long long count=0;
      while(i>=0)
      {
          int j=N-1;
          while(check(X[i],Y[j])==false && j>=0)
          {
              j--;
          }
          count+=j+1;
          i--;
      }
      return count;
   }
0
kingphilosopher03 months ago
class Solution
{
    
   
    static int getIndex(int y[] , int n , int ele){
        
        int low = 0;
        int high = n-1;
        int ans = -1;
        while(low<=high){
            int mid = (low+high)/2;
            if(y[mid] >ele){
                ans = mid;
                high  =mid -1;
            }
            else {
                low = mid+1;
            }
        }
        return ans;
    }
    static long countPairs(int x[], int y[], int M, int N)
    {
        // your code here
        int zeros=0, one=0, two=0,three=0,four=0;
        Arrays.sort(x);
        Arrays.sort(y);
        
        for(int i=0; i<N; i++){
            if(y[i]==0)zeros++;
            if(y[i]==1)one++;
            if(y[i]==2)two++;
            if(y[i]==3)three++;
            if(y[i]==4)four++;
        }
        long ans =0;
        for(int i=0;i<M;i++){
            if(x[i]==0) continue;
            else if(x[i]==1){
                ans+=zeros;
            }else if(x[i]==2){
                int idx = getIndex(y,N,2);
                if(idx!=-1){
                    ans+=N-idx;
                }
                ans-=three;
                ans-=four;
                ans+=one+zeros;
            }else{
                int idx = getIndex(y,N,x[i]);
                if(idx!=-1){
                    ans+=N-idx;
                }
                ans+=one+zeros;
                if(x[i]==3){
                    ans+=two;
                }
            }
        }
        return ans;
0
shubhambhosale04113 months ago
//TLE SOLUTION 
  int cnt=0;     /* for(int i=0;i<M;i++)      {          for(int j=0;j<N;j++)          {              int k=(X[i])^(Y[j]);              int g=(Y[i])^(X[j]);              if(k>g)              {                  cnt++;              }                        }      }*/      for(int i=0;i<M;i++){         for(int j=0;j<N;j++){             if(pow(X[i],Y[j])>pow(Y[j],X[i])){                 cnt++;             }                              }         }      return cnt;
0
ankitbajaj13 months ago
Time Limit Exceeded
 
long long countPairs(int X[], int Y[], int M, int N)   {      //Your code here      long long count =0;      int i=0,j=0,x,y;      while(i<M || j<N)      {          if(j==N && i==(M-1))          {              break;          }          if(j==N && i<M-1)          {              j=0;              i++;          }          x=X[i];          y=Y[j];          if((pow(x,y)) > (pow(y,x)))          {              count++;              if(j==(N-1))              {                  i++;                  j=0;              }              else              {                  j++;              }          }          else          {              j++;          }      }      return count;   }
0
aniruddhrk40123 months ago
#User function Template for python3import bisectclass Solution:    #Function to count number of pairs such that x^y is greater than y^x.        def countPairs(self,a,b,M,N):       #code here       a.sort()       b.sort()       Count = 0       counter = b.count(0)       if counter>0:           Count+=(counter*M)       begInd = bisect.bisect_right(a,1)       a = a[begInd:]       counter = b.count(1)       if counter>0:           Count+=(counter*len(a))       for i in a:           if i==2:               start = 4           else:               start = i           temp = bisect.bisect_right(b,start)           flag = bisect.bisect_left(b,start)           if i==3 and b[flag-1]==2:               counter = b.count(2)               Count+=(1*counter)           Count+=N-temp       return Count#{ #  Driver Code Starts#Initial Template for Python 3
#Initial Template for Python 3
import atexitimport ioimport sysimport bisect
_INPUT_LINES = sys.stdin.read().splitlines()input = iter(_INPUT_LINES).__next___OUTPUT_BUFFER = io.StringIO()sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():   sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__=='__main__':   t = int(input())   for i in range(t):       M,N=map(int,input().strip().split())       a=list(map(int,input().strip().split()))       b=list(map(int,input().strip().split()))       ob=Solution();       print(ob.countPairs(a,b,M,N))       #code here# } Driver Code Ends
-7
trilokjain3 months ago
class Solution{   public:      // X[], Y[]: input arrau   // M, N: size of arrays X[] and Y[] respectively   //Function to count number of pairs such that x^y is greater than y^x.   long long countPairs(int X[], int Y[], int M, int N)   {      //Your code here      long long count=0;      for(int i=0;i<M;i++)      {          for(int j=0;j<N;j++)          {              if(pow(double(X[i]),double(Y[j])) > pow(double(Y[j]),double(X[i])) )              {                  count++;              }          }      }      return count;         }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.