Find pairs with given sum such that pair elements lie in different BSTs in Python

Finding pairs with a given sum from two different Binary Search Trees is a classic problem that combines BST traversal with the two-pointer technique. The key insight is to use the sorted property of BST in-order traversals.

Problem Statement

Given two Binary Search Trees and a target sum, find all pairs where one element comes from the first BST and another from the second BST, and their sum equals the target.

For example, with sum = 12:

BST 1 9 4 11 2 7 BST 2 6 3 19 5 Found Pairs (sum = 12): (6, 6): 6 + 6 = 12 (7, 5): 7 + 5 = 12 (9, 3): 9 + 3 = 12

Algorithm

The solution uses a two-pointer approach on sorted arrays obtained from in-order traversal of both BSTs ?

  1. Perform in-order traversal of both BSTs to get sorted arrays
  2. Use two pointers: left pointer starts from beginning of first array, right pointer starts from end of second array
  3. If sum equals target, add pair and move both pointers
  4. If sum is less than target, move left pointer forward
  5. If sum is greater than target, move right pointer backward

Implementation

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert(root, key):
    if root == None:
        return TreeNode(key)
    if root.data > key:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

def store_inorder(node, traversal):
    if node == None:
        return
    store_inorder(node.left, traversal)
    traversal.append(node.data)
    store_inorder(node.right, traversal)

def find_pairs_with_sum(trav1, trav2, target_sum):
    left = 0
    right = len(trav2) - 1
    pairs = []
    
    while left < len(trav1) and right >= 0:
        current_sum = trav1[left] + trav2[right]
        
        if current_sum == target_sum:
            pairs.append((trav1[left], trav2[right]))
            left += 1
            right -= 1
        elif current_sum < target_sum:
            left += 1
        else:
            right -= 1
            
    return pairs

def get_pairs_from_bsts(root1, root2, target_sum):
    # Get sorted arrays from both BSTs
    trav1 = []
    trav2 = []
    
    store_inorder(root1, trav1)
    store_inorder(root2, trav2)
    
    return find_pairs_with_sum(trav1, trav2, target_sum)

# Create first BST
root1 = None
for element in [9, 11, 4, 7, 2, 6, 15, 14]:
    root1 = insert(root1, element)

# Create second BST  
root2 = None
for element in [6, 19, 3, 2, 4, 5]:
    root2 = insert(root2, element)

# Find pairs with sum = 12
target_sum = 12
result = get_pairs_from_bsts(root1, root2, target_sum)
print(f"Pairs with sum {target_sum}: {result}")
Pairs with sum 12: [(6, 6), (7, 5), (9, 3)]

How It Works

The algorithm leverages the sorted property of BST in-order traversals. Since both arrays are sorted, we can use the two-pointer technique efficiently ?

  • In-order traversal of BST gives elements in ascending order
  • Two pointers start from opposite ends of the arrays
  • Time complexity: O(m + n) where m and n are the sizes of the BSTs
  • Space complexity: O(m + n) for storing the traversals

Key Points

  • Each pair contains one element from each BST
  • The solution handles duplicate values correctly
  • Works efficiently even with large BSTs due to linear time complexity
  • No need to check all possible combinations (which would be O(m×n))

Conclusion

This approach efficiently finds pairs with a given sum from two BSTs using in-order traversal and the two-pointer technique. The algorithm runs in linear time and is optimal for this problem.

Updated on: 2026-03-25T09:22:41+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements