πDay 12. 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.
π Example Walkthrough:
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.
π Solution Code
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