Find pairs with given sum such that pair elements lie in different BSTs
Given two Binary Search Trees (BST) and a given sum. The task is to find pairs with given sum such that each pair elements must lie in different BST.
Input : sum = 10 8 5 / \ / \ 3 10 2 18 / \ \ / \ 1 6 14 1 3 / \ / \ 5 7 13 4 Output : (5,5), (6,4), (7,3), (8,2) In above pairs first element lies in first BST and second element lies in second BST
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
A simple solution for this problem is to store Inorder traversal of one tree in auxiliary array then pick element one by one from the array and find its pair in other tree for given sum. Time complexity for this approach will be O(n2) if total nodes in both the trees are equal.
An efficient solution for this solution is to store Inorder traversals of both BSTs in two different auxiliary arrays vect1 and vect2. Now we follow method1 of this article. Since Inorder traversal of BST is always gives sorted sequence, we don not need to sort our arrays.
- Take iterator left and points it to the left corner vect1.
- Take iterator right and points it to the right corner vect2.
- Now if vect11[left] + vect2[right] < sum then move left iterator in vect1 in forward direction i.e; left++.
- Now if vect1[left] + vect2[right] > sum then move right iterator in vect in backward direction i.e; right–.
Below is implementation of above idea.
Time complexity : O(n)
Auxiliary space : O(n)
We have another space optimized approach to solve this problem. The idea is to convert bst into doubly linked list and apply above method for doubly linked list.See this article.
Time complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.