13. Pair Sum in BST
The problem can be found at the following link: Question Link
Problem Description
Given a Binary Search Tree (BST) and a target value, check whether there exists a pair of nodes in the BST whose sum equals the given target.
Examples
Example 1:
Input:
7
/ \
3 8
/ \ \
2 4 9Target = 12
Output:
TrueExplanation:
In the given BST, there exist two nodes (8 and 4) that sum up to 12.
Example 2:
Input:
Target = 23
Output:
Explanation:
No pair of nodes in the BST sum up to 23.
Constraints:
$(1 \leq \text{Number of Nodes} \leq 10^5)$
$(1 \leq \text{target} \leq 10^6)$
My Approach
Optimized Two-Pointer on Inorder Traversal (O(N) Time, O(N) Space)
O(N) Time, O(N) Space)Convert BST to sorted array using inorder traversal.
Use two-pointer approach (left and right) to find the target sum efficiently.
Algorithm Steps:
Perform an inorder traversal and store the BST elements in a sorted list.
Use two pointers (
leftat the start,rightat the end) and check the sum:If
arr[left] + arr[right] == target, returntrue.If
arr[left] + arr[right] < target, moveleft++.If
arr[left] + arr[right] > target, moveright--.
If no such pair exists, return
false.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N), since we traverse each node once.Expected Auxiliary Space Complexity:
O(N), due to storing the inorder traversal.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated