Count pairs in BST with sum greater than K
Given a binary search tree containing N distinct nodes and a value K. The task is to count pairs in the given binary search tree whose sum is greater than the given value K.
Input: 5 / \ 3 7 / \ / \ 2 4 6 8 k = 11 Output: 6 Explanation: There are 6 pairs which are (4, 8), (5, 7), (5, 8), (6, 7), (6, 8) and (7, 8). Input: 8 / \ 3 9 \ / \ 5 6 18 k = 23 Output: 3 Explanation: There are 3 pairs which are (6, 18), (8, 18) and (9, 18).
To solve the problem mentioned above we have to store inorder traversal of BST in an array then run two loops to generate all pairs and one by one check if the current pair’s sum is greater than k or not.
The above method can be optimized if we store the inorder traversal of BST in an array and take the initial and last index of the array in l and r variable to find the total pair in the inorder array. Initially assign l as 0 and r as n-1. Consider a variable and initialize it to zero. This variable result will be our final answer. Now iterate until l < r and if the current left and current right have a sum greater than K, all elements from l+1 to r form a pair with it otherwise it doesn’t, therefore, increment current left. Finally, return the result.
Below is the implementation of the above approach:
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.