Two Sum in BST in DSA Javascript - Time & Space Complexity
We want to know how long it takes to find two numbers in a BST that add up to a target.
How does the time grow as the tree gets bigger?
Analyze the time complexity of the following code snippet.
function findTarget(root, k) {
const set = new Set();
function dfs(node) {
if (!node) return false;
if (set.has(k - node.val)) return true;
set.add(node.val);
return dfs(node.left) || dfs(node.right);
}
return dfs(root);
}
This code searches the BST to find if two values sum to k using a set to track seen values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive traversal of each node in the BST.
- How many times: Each node is visited once during the depth-first search.
As the number of nodes grows, the function visits each node once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to find the two sum grows linearly with the number of nodes in the tree.
[X] Wrong: "Because the tree is sorted, we can find the pair in less than linear time."
[OK] Correct: The code visits every node once to check pairs, so it still takes time proportional to the tree size.
Understanding how traversal and lookups combine helps you explain your approach clearly and confidently.
"What if we used an in-order traversal to get a sorted array first, then used 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: Identify the goal
The goal is to check if such a pair exists, not to find max value, count nodes, or check balance.Final Answer:
Find two nodes in the BST whose values add up to a target sum. -> Option BQuick Check:
Two Sum in BST = Find pair with target sum [OK]
- Confusing with finding max or min value
- Thinking it counts nodes instead of pairs
- Assuming it checks tree balance
Solution
Step 1: Check correct property assignments
function Node(val) { this.val = val; this.left = null; this.right = null; } correctly assignsthis.val,this.left, andthis.rightto initialize a BST node.Step 2: Identify syntax and property errors in other options
let Node = (val) => { val = val; left = null; right = null; } missesthiskeyword and uses arrow function incorrectly. class Node { constructor(val) { val = val; left = null; right = null; } } assigns to local variables, notthis. var Node = function(val) { this.value = val; this.left = this.right = undefined; } usesthis.valueinstead ofthis.valand sets children toundefinedinstead ofnull.Final Answer:
function Node(val) { this.val = val; this.left = null; this.right = null; } -> Option AQuick Check:
Correct node declaration usesthis.valand null children [OK]
- Forgetting 'this' keyword for properties
- Using arrow functions for constructor
- Assigning children to undefined instead of null
findTarget(root, 9) return?5 / \ 3 6 / \ \ 2 4 7
Assuming
findTarget returns true if two nodes sum to target, else false.Solution
Step 1: Identify pairs that sum to 9
Check pairs: 2+7=9, 3+6=9, 4+5=9. All these pairs exist in the BST.Step 2: Confirm function returns true if any pair matches
Since pairs exist,findTargetreturnstrue.Final Answer:
true -> Option AQuick Check:
Pairs sum to 9 = true [OK]
- Ignoring valid pairs in BST
- Assuming function returns node instead of boolean
- Confusing null or undefined as return
function findTarget(root, k) {
const set = new Set();
function dfs(node) {
if (!node) return false;
if (set.has(k - node.val)) return true;
set.add(node.val);
dfs(node.left);
dfs(node.right);
}
return dfs(root);
}What is the main bug causing incorrect results?
Solution
Step 1: Analyze recursive calls in dfs
The recursive calls todfs(node.left)anddfs(node.right)do not return their results, so true found deeper is ignored.Step 2: Fix by returning recursive calls
Addingreturnbefore recursive calls ensures if true is found, it propagates up and final result is correct.Final Answer:
Missing return statements in recursive calls inside dfs -> Option CQuick Check:
Return recursive calls to propagate true [OK]
- Not returning recursive call results
- Confusing Set usage as bug
- Ignoring base case handling
Solution
Step 1: Understand space complexity of approaches
Storing all nodes uses O(n) space. BFS also uses O(n) space. Converting to linked list uses O(n).Step 2: Use two iterators approach
Using two iterators (one in-order for smallest, one reverse in-order for largest) uses O(h) space, where h is tree height, optimizing space.Final Answer:
Use two iterators: one in-order and one reverse in-order traversal simultaneously. -> Option DQuick Check:
Two iterators = O(h) space optimization [OK]
- Using full array storage increasing space to O(n)
- Trying BFS which uses more space
- Converting BST to linked list wastes space
Ready to prove it?
Pass the test and this pattern moves unknown
