Two Sum in BST in DSA Rust - Time & Space Complexity
We want to understand how long it takes to find two numbers in a Binary Search Tree that add up to a target.
How does the time needed grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
fn find_target(root: &Option>, k: i32) -> bool {
let mut nums = Vec::new();
fn inorder(node: &Option>, nums: &mut Vec) {
if let Some(n) = node {
inorder(&n.left, nums);
nums.push(n.val);
inorder(&n.right, nums);
}
}
inorder(root, &mut nums);
let (mut left, mut right) = (0, nums.len() - 1);
while left < right {
let sum = nums[left] + nums[right];
if sum == k { return true; }
else if sum < k { left += 1; }
else { right -= 1; }
}
false
}
This code finds if two values in a BST add up to a target by first collecting values in order, then using two pointers to find the sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inorder traversal of the BST to collect values.
- How many times: Visits each node once, so n times for n nodes.
- Secondary operation: Two-pointer loop scanning the sorted array.
- How many times: At most n times, moving pointers inward.
As the tree size grows, the number of nodes visited grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 for traversal + 10 for two-pointer scan) |
| 100 | About 200 (100 + 100) |
| 1000 | About 2000 (1000 + 1000) |
Pattern observation: Operations grow roughly twice the number of nodes, so growth is linear.
Time Complexity: O(n)
This means the time needed grows directly with the number of nodes in the tree.
[X] Wrong: "Because the tree is sorted, we can find the two numbers in less than linear time without visiting all nodes."
[OK] Correct: We must at least look at all nodes once to be sure, so the traversal takes linear time.
Understanding this helps you explain how tree traversal and two-pointer techniques combine efficiently, a useful skill for many coding problems.
"What if we used a hash set during traversal instead of sorting and two pointers? How would the time complexity change?"
Practice
Two Sum in BST problem?Solution
Step 1: Understand the problem statement
The problem asks to find two nodes in a Binary Search Tree (BST) such that their values add up to a given target sum.Step 2: Clarify the goal
We need to check if any pair of nodes exists with values summing to the target, not just find max or count nodes.Final Answer:
Find two nodes in the BST whose values add up to a target sum. -> Option AQuick Check:
Two Sum in BST = Find pair with target sum [OK]
- Thinking it asks for max value only
- Confusing with counting nodes
- Assuming BST must be balanced
Solution
Step 1: Understand Rust ownership and recursive types
Rust requires recursive types like BST nodes to use Box or other smart pointers to allocate on heap.Step 2: Check each option
struct TreeNode { val: i32, left: Option, right: Option } uses Option which is correct. struct TreeNode { val: i32, left: TreeNode, right: TreeNode } and D use direct TreeNode which is invalid recursive type. struct TreeNode { val: i32, left: &TreeNode, right: &TreeNode } uses references without lifetimes, which is incorrect.Final Answer:
struct TreeNode { val: i32, left: Option, right: Option } -> Option BQuick Check:
Use Box for recursive BST nodes in Rust [OK]
- Using direct TreeNode type causing infinite size error
- Using references without lifetimes
- Omitting Option for nullable children
5
/ \
3 6
/ \ \
2 4 7
Rust code snippet:
fn find_target(root: &Option, k: i32) -> bool {
let mut set = std::collections::HashSet::new();
fn dfs(node: &Option, k: i32, set: &mut std::collections::HashSet<i32>) -> bool {
if let Some(n) = node {
if set.contains(&(k - n.val)) {
return true;
}
set.insert(n.val);
dfs(&n.left, k, set) || dfs(&n.right, k, set)
} else {
false
}
}
dfs(root, k, &mut set)
}Solution
Step 1: Trace DFS with HashSet on BST nodes
Start at root 5, set is empty. Check if complement 9-5=4 in set? No. Insert 5. Check left child 3: complement 9-3=6, 6 not in set. Insert 3. Check left 2: complement 9-2=7, 7 not in set. Insert 2. Check right 4: complement 9-4=5, 5 is in set, so return true.Step 2: Confirm early return on finding pair
Since pair (5,4) sums to 9, function returns true immediately.Final Answer:
true -> Option AQuick Check:
Pair found (5+4=9) = true [OK]
- Not inserting current node before checking complement
- Returning false too early
- Ignoring left or right subtree
fn find_target(root: &Option, k: i32) -> bool {
let mut set = std::collections::HashSet::new();
fn dfs(node: &Option, k: i32, set: &mut std::collections::HashSet<i32>) -> bool {
if let Some(n) = node {
set.insert(n.val);
if set.contains(&(k - n.val)) {
return true;
}
dfs(&n.left, k, set) || dfs(&n.right, k, set)
} else {
false
}
}
dfs(root, k, &mut set)
}Solution
Step 1: Analyze order of operations in DFS
The code inserts current node value into set before checking if complement exists. This causes the complement check to always find current value itself, leading to false positive.Step 2: Correct approach
Check if complement exists in set first, then insert current node value to avoid matching node with itself.Final Answer:
Inserting current node value before checking complement causes false positive. -> Option DQuick Check:
Check complement before insert to avoid false positive [OK]
- Inserting before checking complement
- Ignoring early return on true
- Not handling None nodes
Solution
Step 1: Understand space constraints and BST properties
Storing all nodes uses O(n) space. Using BST inorder iterator yields sorted values with O(h) space.Step 2: Use two iterators moving inward
One iterator moves from smallest to largest (inorder), another from largest to smallest (reverse inorder). Compare sums and move iterators accordingly to find target sum efficiently.Step 3: Compare with other options
Traverse BST in preorder and store all values in a vector, then use two pointers on vector. uses O(n) space. Use a HashSet to store visited nodes and check complements during DFS. uses HashSet with O(n) space. Convert BST to linked list and then check pairs sequentially. is inefficient and uses extra space.Final Answer:
Use two iterators: one from smallest to largest, another from largest to smallest, moving inward to find target sum. -> Option CQuick Check:
Two BST iterators inward = O(h) space Two Sum [OK]
- Using full traversal storing all nodes
- Ignoring space complexity
- Not using reverse inorder iterator
Ready to prove it?
Pass the test and this pattern moves unknown
