Skip to content

Commit 2d4cfb5

Browse files
committed
feat(algorithms, arrays, two-sum): two sum input as bst
1 parent 7f2ad34 commit 2d4cfb5

20 files changed

+153
-43
lines changed

algorithms/arrays/two_sum/README.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,74 @@ Output: [1,2]
3535
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
3636
```
3737

38+
---
39+
40+
# Two Sum IV - Input Is a BST
41+
42+
Given the root of a binary search tree and an integer k, determine whether there are two elements in the BST whose sum
43+
equals k. Return TRUE if such elements exist or FALSE otherwise.
44+
45+
## Constraints
46+
47+
- The number of nodes in the tree is in the range [1, 10^3].
48+
- 10^3 <= Node.data <= 10^3
49+
- root is guaranteed to be a valid binary search tree.
50+
- 10^4 <= k <= 10^4
51+
52+
## Examples
53+
54+
![Example 1](./images/examples/two_sum_4_input_is_bst_example_1.png)
55+
![Example 2](./images/examples/two_sum_4_input_is_bst_example_2.png)
56+
![Example 3](./images/examples/two_sum_4_input_is_bst_example_3.png)
57+
58+
## Solution
59+
60+
The core intuition behind solving this problem is to use a set to track values encountered during a breadth-first search
61+
of the binary search tree (BST). We calculate each node’s complement (i.e., the difference between k and the node’s value)
62+
and check if this complement already exists in the set. If it does, it means there is another node in the BST whose value,
63+
when added to the current node’s value, equals k, and we return TRUE. Otherwise, we add the current node’s value to the set.
64+
If no two nodes with the required sum are found by the end of the traversal, we return FALSE.
65+
66+
Using the intuition above, the solution can be implemented as follows:
67+
68+
1. If the BST is empty, return FALSE.
69+
2. Define a set, seen, to store the visited node values.
70+
3. Define a queue, q, to perform the level-order traversal of the BST.
71+
- Enqueue root to q to start the traversal from the root node.
72+
4. While the queue is not empty, repeat the following steps:
73+
- Dequeue a node from the front of the queue.
74+
- Check if the complement of the current node’s value exists in the seen set. If yes, return TRUE.
75+
- Add the current node’s value to the seen set.
76+
- Enqueue its left and right children.
77+
5. If no two nodes with the required sum are found, return FALSE.
78+
79+
Let’s look at the following illustration to get a better understanding of the solution:
80+
81+
![Solution 1](./images/solutions/two_sum_4_input_is_bst_solution_1.png)
82+
![Solution 2](./images/solutions/two_sum_4_input_is_bst_solution_2.png)
83+
![Solution 3](./images/solutions/two_sum_4_input_is_bst_solution_3.png)
84+
![Solution 4](./images/solutions/two_sum_4_input_is_bst_solution_4.png)
85+
![Solution 5](./images/solutions/two_sum_4_input_is_bst_solution_5.png)
86+
![Solution 6](./images/solutions/two_sum_4_input_is_bst_solution_6.png)
87+
![Solution 7](./images/solutions/two_sum_4_input_is_bst_solution_7.png)
88+
![Solution 8](./images/solutions/two_sum_4_input_is_bst_solution_8.png)
89+
![Solution 9](./images/solutions/two_sum_4_input_is_bst_solution_9.png)
90+
![Solution 10](./images/solutions/two_sum_4_input_is_bst_solution_10.png)
91+
![Solution 11](./images/solutions/two_sum_4_input_is_bst_solution_11.png)
92+
![Solution 12](./images/solutions/two_sum_4_input_is_bst_solution_12.png)
93+
![Solution 13](./images/solutions/two_sum_4_input_is_bst_solution_13.png)
94+
![Solution 14](./images/solutions/two_sum_4_input_is_bst_solution_14.png)
95+
96+
### Time Complexity
97+
98+
The algorithm’s time complexity is O(n), where n is the number of nodes in the binary search tree.
99+
100+
### Space Complexity
101+
102+
The algorithm’s space complexity is O(n), as the size of the set can grow up to at most n.
103+
104+
---
105+
38106
## Related Topics
39107

40108
- Array

algorithms/arrays/two_sum/__init__.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from typing import List
1+
from typing import List, Deque, Set
2+
from collections import deque
3+
from datastructures.trees.binary.node import BinaryTreeNode
24

35

46
def two_sum(numbers: List[int], target: int) -> List[int]:
@@ -59,3 +61,44 @@ def two_sum_with_pointers(numbers: List[int], target: int) -> List[int]:
5961
first_pointer += 1
6062
else:
6163
last_pointer -= 1
64+
return []
65+
66+
67+
def two_sum_find_target(root: BinaryTreeNode, k: int) -> bool:
68+
"""
69+
Checks if two nodes in the binary search tree add up to the given target number
70+
71+
Args:
72+
root (BinaryTreeNode): root of the binary search tree
73+
k (int): target number
74+
Returns:
75+
bool: True if there are two nodes in the binary search tree that add up to the target, False otherwise
76+
"""
77+
if not root:
78+
return False
79+
80+
# store the seen values so far during the traversal
81+
seen: Set[int] = set()
82+
83+
# Keep track of visited nodes, we start with the root node. We use a FIFO queue here
84+
queue: Deque[BinaryTreeNode] = deque()
85+
queue.append(root)
86+
87+
while queue:
88+
# dequeue the first node, the front of the queue.
89+
curr = queue.popleft()
90+
91+
if curr:
92+
# check if the complement of this node's value exists in the values we have seen so far
93+
if (k - curr.data) in seen:
94+
return True
95+
96+
# if not, add the value
97+
seen.add(curr.data)
98+
99+
# enqueue the left and right children of the current node
100+
queue.append(curr.left)
101+
queue.append(curr.right)
102+
103+
# if we reach here, we have not found two nodes that add up to the target
104+
return False
98.5 KB
Loading
86.5 KB
Loading
69.5 KB
Loading
62.6 KB
Loading
117 KB
Loading
92.2 KB
Loading
120 KB
Loading
99.4 KB
Loading

0 commit comments

Comments
 (0)