Count pairs from 2 BST whose sum is equal to given value "X"
Pattern: Two sum in BST
Walk the first BST in increasing order and the second in decreasing order. If the sum is x, count it and move both; if it is too small, move the first one up; if too large, move the second one down. Each walk is an iterator with a stack.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given two BSTs (values distinct within each) and x, return how many pairs (a value from the first, a value from the
second) add up to x. The example gives 3. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- How would you do this with two sorted arrays?
- Which iterators give those orders?
- What happens after a match?
Hints
Brute force, and why it fails
For each value of the first tree, search the second for x - v: O(m h2).
The key insight
The two iterators turn the problem into two pointers on two sorted streams, in linear time.
Dry run
| count | 0 |
|---|
a = [5, 3, 7, 2, 4, 6, 8], b = [10, 6, 15, 3, 8, 11, 18], x = 16. Start: 2 (smallest of a) and 18 (largest of b): 20, too big.
The plan
lo = ascending iterator on a; hi = descending iterator on b
while both have values: s = lo + hi
if s == x: count; move both elif s < x: move lo else: move hi
Complexity
- Time
O(m + n)- Space
O(h1 + h2)
Each node is visited once.
Edge cases
- One tree empty: 0.
- No pairs.
- Every value pairs.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int countPairs(TreeNode a, TreeNode b, int x) {
Deque<TreeNode> lo = new ArrayDeque<>(), hi = new ArrayDeque<>(); // a ascending, b descending
TreeNode p = a, q = b;
int count = 0;
while (true) {
for (; p != null; p = p.left) lo.push(p);
for (; q != null; q = q.right) hi.push(q);
if (lo.isEmpty() || hi.isEmpty()) return count;
int s = lo.peek().val + hi.peek().val;
if (s == x) count++;
if (s <= x) p = lo.pop().right; // too small (or used): a's next larger value
if (s >= x) q = hi.pop().left; // too big (or used): b's next smaller value
}
}
}C++
class Solution {
public:
int countPairs(TreeNode* a, TreeNode* b, int x) {
stack<TreeNode*> lo, hi; // a ascending, b descending
TreeNode* p = a;
TreeNode* q = b;
int count = 0;
while (true) {
for (; p != NULL; p = p->left) lo.push(p);
for (; q != NULL; q = q->right) hi.push(q);
if (lo.empty() || hi.empty()) return count;
int s = lo.top()->val + hi.top()->val;
if (s == x) count++;
if (s <= x) { p = lo.top()->right; lo.pop(); } // too small (or used): a's next larger value
if (s >= x) { q = hi.top()->left; hi.pop(); } // too big (or used): b's next smaller value
}
}
};Python
class Solution:
def countPairs(self, a, b, x: int) -> int:
lo, hi, p, q, count = [], [], a, b, 0 # a ascending, b descending
while True:
while p:
lo.append(p)
p = p.left
while q:
hi.append(q)
q = q.right
if not lo or not hi:
return count
s = lo[-1].val + hi[-1].val
if s == x:
count += 1
if s <= x:
p = lo.pop().right # too small (or used): a's next larger value
if s >= x:
q = hi.pop().left # too big (or used): b's next smaller valueCommon mistakes
- Moving only one side after a match.
- Comparing every pair.