Two Sum IV - Input is a BST — Solution in Python, Java & C++
Two Sum IV - Input is a BST solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Two Sum IV - Input is a BST is an easy coding problem on hash table, depth-first search and two pointers, asked in Amazon, Microsoft and Meta interviews.
- Difficulty: Easy
- Topics: Hash Table, Depth-First Search, Two Pointers, Trees
- Asked at: Amazon, Microsoft, Meta
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given the root of a binary search tree with distinct values and an integer k, return true if there are two different nodes whose values add up to k, and false otherwise.
Example 1
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Explanation: For example 2 + 7 = 9 (and 3 + 6, 4 + 5).
Example 2
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Explanation: The two largest values add up to only 13.
Example 3
Input: root = [1], k = 2
Output: false
Explanation: 1 + 1 would use the same node twice.
Constraints
The number of nodes in the tree is in the range [1, 10^4]-10^4 <= Node.val <= 10^4All values in the tree are distinct-10^5 <= k <= 10^5
Hints for Two Sum IV - Input is a BST
Hint 1
This is Two Sum, with the numbers stored in a tree instead of an array.
Hint 2
Walk the tree; for each value
v, ask whetherk - vhas already been seen. A hash set answers in O(1).Hint 3
Alternatively, an inorder walk gives the values sorted, and two pointers from both ends find a pair in one pass.
How to solve Two Sum IV - Input is a BST
Visit every node once, keeping a set of the values seen so far. A pair summing to k exists exactly when, at some node, its complement k - val is already in the set.
Approach
- Start with an empty set and traverse the tree (any order).
- At each node with value
v: ifk - vis in the set, returntrue. - Otherwise add
vto the set and continue. - If the traversal ends, return
false.
Why it works
If nodes a and b (visited in that order) satisfy a + b = k, then when b is visited a is already in the set and the check succeeds. Conversely the check only succeeds against a value stored at a different, earlier node, so the same node is never used twice.
Complexity
- Time —
O(n) - Space —
O(n) for the set (the sorted-list two-pointer version also needs O(n), or O(h) with two BST iterators)
Pitfalls
- Check the complement before inserting the current value, or
v + v = kwould match a single node. - The BST order is not needed for the hash-set solution — it is what makes the two-pointer one possible.
Reference solution
Python
from typing import Optional
def findTarget(root: Optional[TreeNode], k: int) -> bool:
seen = set()
stack = [root] if root is not None else []
while stack:
node = stack.pop()
if k - node.val in seen:
return True
seen.add(node.val)
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
return FalseJava
public static boolean findTarget(TreeNode root, int k) {
Set<Integer> seen = new HashSet<>();
Deque<TreeNode> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (seen.contains(k - node.val)) return true;
seen.add(node.val);
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
return false;
}C++
bool findTarget(TreeNode* root, int k) {
unordered_set<int> seen;
vector<TreeNode*> stack;
if (root) stack.push_back(root);
while (!stack.empty()) {
TreeNode* node = stack.back();
stack.pop_back();
if (seen.count(k - node->val)) return true;
seen.insert(node->val);
if (node->left) stack.push_back(node->left);
if (node->right) stack.push_back(node->right);
}
return false;
}JavaScript
var findTarget = function(root, k) {
var seen = new Set();
var stack = root === null ? [] : [root];
while (stack.length > 0) {
var node = stack.pop();
if (seen.has(k - node.val)) return true;
seen.add(node.val);
if (node.left !== null) stack.push(node.left);
if (node.right !== null) stack.push(node.right);
}
return false;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 439 hash table problems · the whole catalogue
Learn the technique: Hashing: Hash Maps and Hash Sets · Depth-First Search (DFS)