Brothers From Different Roots | Practice | GeeksforGeeks

Given two BSTs containing N1 and N2 distinct nodes respectively and given a value x. Your task is to complete the function countPairs(), that returns the count of all pairs from both the BSTs whose sum is equal to x.

Example 1:
Input:
BST1:
       5
     /   \
    3     7
   / \   / \
  2   4 6   8

BST2:
       10
     /    \
    6      15
   / \    /  \
  3   8  11   18

x = 16
Output:
3
Explanation:
The pairs are: (5, 11), (6, 10) and (8, 8)

 
Example 2:
Input:
BST1:
  1
   \
    3
   /
  2
BST2:
    3
   / \
  2   4
 /     
1

x = 4
Output:
3
Explanation:
The pairs are: (2, 2), (3, 1) and (1, 3)


Your Task:
You don't need to read input or print anything. Your task is to complete the function countPairs(), which takes 2 BST's as parameter in form of root1 and root2 and the integer x, that returns the count of all pairs from both the BSTs whose sum is equal to x.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 106
+1
aakashjangra774 days ago
void inorder(Node* root,map<int,int> &store){   if(root==NULL)   {       return ;   }      inorder(root->left,store);   store[root->data]=1;   inorder(root->right,store);   }
   int countPairs(Node* root1, Node* root2, int X)   {       map<int,int> store1,store2;              inorder(root1,store1);       inorder(root2,store2);       int count=0;              for(auto i:store1)       {           if(store2[X-i.first]==1)           {               count++;                          }       }              return count;
   }
+1
ricardo991 week ago
int ans=0; // Global Variable to hold the ans 
void find(Node* root, unordered_set<int> &s, int x)
{
   if(root==NULL)
   return;
   if(s.find(x-root->data)!=s.end())
   ans++;
   find(root->left, s, x);
   find(root->right, s, x);
}
void fill2nd(Node* root, unordered_set<int>& s)
{
   if(root==NULL)
   return;
   s.insert(root->data);
   fill2nd(root->left, s);
   fill2nd(root->right, s);
}
   int countPairs(Node* root1, Node* root2, int x)
   {
       unordered_set<int> s;
       fill2nd(root2, s);
       find(root1, s, x);
       return ans;
   }
0
aryankhatana352 weeks ago
class Solution{public:int c;   bool fetch(Node*root2,int k){       if(root2==NULL){           return false;       }       // if(!root2) return false;       if(k==root2->data){           return true;       }       bool x,y;       x=false;       y=false;       if(k<root2->data){           x=fetch(root2->left,k);       }       else if(k>root2->data){           y=fetch(root2->right,k);       }       return x or y;   }      void solve(Node* root1, Node* root2, int k){       if(root1==NULL){           return;       }       solve(root1->left,root2,k);       if(fetch(root2,k-root1->data)){           c++;       }       solve(root1->right,root2,k);   }       int countPairs(Node* root1, Node* root2, int x)   {    c=0;    solve(root1,root2,x);    return c;   }};
+1
raj22202 weeks ago
// Java Sloution with O(n) time complexity and O(n) Space Complexity
 
class Solution{public static int countPairs(Node root1, Node root2, int x){ ArrayList<Integer> in1 = new ArrayList<>(); ArrayList<Integer> in2 = new ArrayList<>(); inOrder(root1, in1); inOrder(root2, in2);  int  i = 0; int j = in2.size()-1; int count = 0; while(i < in1.size() && j >= 0) {     int sum = in1.get(i) + in2.get(j) ;     if(sum == x)     {         count++;         i++;         j--;     }     else if(sum < x)     {         i++;     }     else     {         j--;     } }  return count; }public static void inOrder(Node root, ArrayList<Integer> in){    if(root == null)    {        return;    }    inOrder(root.left, in);    in.add(root.data);    inOrder(root.right, in);}}
+1
sgupta95191 month ago
class Solution
{
public static int countPairs(Node root1, Node root2, int x)
{
 // Code here
 if(root1==null)
 return 0;
 return chec(root2,x-root1.data)+countPairs(root1.left,root2,x)+countPairs(root1.right,root2,x);
}
static int chec(Node root2, int x)
{
    if(root2==null)
    return 0;
    if(root2.data==x)
    return 1;
    if(root2.data<x)
    return chec(root2.right,x);
    return chec(root2.left,x);
    
}
}
0
ahmadsahil261 month ago
class Solution{         public static void inorder(Node root,ArrayList<Integer> list){              if(root==null)           return;              inorder(root.left,list);       list.add(root.data);       inorder(root.right,list);                 }   public static int countPairs(Node root1, Node root2, int x){ // Code here ArrayList<Integer> first = new ArrayList<>(); ArrayList<Integer> second = new ArrayList<>(); inorder(root1,first); inorder(root2,second); int i = 0; int j = second.size()-1; int count = 0; while(i<first.size()&&j>=0){     int a = first.get(i);     int b = second.get(j);     if(a+b==x){         count++;         i++;         j--;     }     else if(a+b<x){                  i++;              }else         j--;           }  return count;  }}
0
milindprajapatmst191 month ago
Linear Space and Complexity.

const int N = 1e6;
int _hash[N + 1];
class Solution {
public:
    void inorder(Node* root, int x, int k, int& cnt) {
        if (!root)
            return;
        inorder(root->left, x, k, cnt);
        if (k && x - root->data > 0 && x - root->data <= N)
            cnt += _hash[x - root->data];
        else if (!k)
            _hash[root->data]++;
        inorder(root->right, x, k, cnt);
    }
    int countPairs(Node* root1, Node* root2, int x) {
        memset(_hash, 0, sizeof(_hash));
        int cnt = 0;
        inorder(root1, x, 0, cnt);
        inorder(root2, x, 1, cnt);
        return cnt;
    }
};
+1
sfazal0001 month ago
int cnt;
bool pairs(node* root1 , int k){   if(!root1) return false;      if(k == root1->data)       return true;       bool x = false;   bool y = false;       if(k< root1->data)   {        x = pairs(root1->left, k);  }  else  if(k> root1->data)  {         y = pairs(root1->right ,k);  }      return x or y;}
 
void solve(node* root , node* root1 , int k){   if(!root and root1) return ;            solve(root->left, root1,k);      if(pairs(root1, k-root->data))    {       cnt++;   }      solve(root->right, root1,k);}            
 
int countPairs(node* root, node* root1, int k){   if(!root) return 0;      cnt =0;      solve(root, root1,k);      return cnt;}   
+1
golaravi5552 months ago
 void inorder(Node *root,vector<int>&v){       if(!root)return;       inorder(root->left,v);       v.push_back(root->data);       inorder(root->right,v);   }   int countPairs(Node* root1, Node* root2, int x)   {        vector<int>v1,v2;        inorder(root1,v1);        inorder(root2,v2);        unordered_set<int> s(v1.begin(),v1.end());              int ct = 0;        for(int i = 0; i < v2.size(); i++){          if(s.find(x - v2[i]) != s.end()) ct++;         }        return ct;   }
0
sanketbhagat2 months ago
SMPLE JAVA SOLUTION
class Solution{
    
    static void inorder(Node root,Set<Integer> set){
        if(root==null) return;
        inorder(root.left,set);
        set.add(root.data);
        inorder(root.right,set);
    }
    
	public static int countPairs(Node root1, Node root2, int x){
		// Code here
		Set<Integer> set1 = new HashSet();
		inorder(root1,set1);
		Set<Integer> set2 = new HashSet<>();
		inorder(root2,set2);
		int ans = 0;
		for(int i: set1) if(set2.contains(x-i)) ans++;
		return ans;
	}
}
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.