close
close
leetcode two sum iv - input is a bst

leetcode two sum iv - input is a bst

3 min read 18-09-2024
leetcode two sum iv - input is a bst

In the world of coding interviews and algorithm practice, the LeetCode problem “Two Sum IV - Input is a BST” stands out. This problem requires a blend of understanding binary search trees (BST) and efficient searching strategies. In this article, we'll break down the problem, explore its common solutions, and offer practical examples to enhance your understanding.

Problem Definition

The problem states:

Given a Binary Search Tree (BST) and an integer k, you need to determine if there exist two elements in the BST such that their sum equals k.

Example

Consider the following BST:

      5
     / \
    3   6
   / \
  2   4
 /
1

If k = 9, the output should be true because 4 + 5 = 9.

If k = 28, the output should be false since no such pair exists.

Common Solutions

1. In-Order Traversal with Set

One of the most common approaches to solving this problem involves utilizing in-order traversal to create a sorted array from the BST. Then, you can use the two-pointer technique or a hash set to find the required pair.

Implementation Example

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        values = set()
        
        def inorder(node):
            if not node:
                return False
            if inorder(node.left):
                return True
            if k - node.val in values:
                return True
            values.add(node.val)
            return inorder(node.right)
        
        return inorder(root)

Explanation

  1. In-Order Traversal: This function goes through the BST in sorted order.
  2. Set Usage: We store each visited node's value in a set. For every node, we check if k - node.val exists in the set. If it does, that means we have found our pair and return True.
  3. Time Complexity: The time complexity of this solution is O(n), where n is the number of nodes in the BST, since we traverse each node once.

2. Using a BST Iterator

An alternative approach is to use an iterator that generates the next smallest and the next largest elements of the BST. By using two iterators, one starting from the smallest value and the other from the largest, we can traverse towards the middle until we find the sum.

Implementation Example

class BSTIterator:
    def __init__(self, root):
        self.stack = []
        self.push_left(root)

    def push_left(self, node):
        while node:
            self.stack.append(node)
            node = node.left

    def next(self):
        node = self.stack.pop()
        self.push_left(node.right)
        return node.val

    def has_next(self):
        return len(self.stack) > 0

class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        if not root:
            return False

        left_iterator = BSTIterator(root)
        right_iterator = BSTIterator(root)

        left_value = left_iterator.next()
        right_value = right_iterator.next()

        while left_value < right_value:
            current_sum = left_value + right_value
            if current_sum == k:
                return True
            elif current_sum < k:
                if left_iterator.has_next():
                    left_value = left_iterator.next()
                else:
                    break
            else:
                if right_iterator.has_next():
                    right_value = right_iterator.next()
                else:
                    break

        return False

Explanation

  1. Two Iterators: We create two iterators, left_iterator for the smallest values and right_iterator for the largest.
  2. While Loop: As long as left_value is less than right_value, we check if their sum equals k, adjusting values accordingly.
  3. Space Complexity: This method uses O(h) space, where h is the height of the BST due to the stack used in the iterator.

Additional Insights

Why Choose One Method Over the Other?

  • In-Order Traversal with Set: Simpler to implement and understand, but uses additional space for the set.
  • BST Iterator: More space-efficient and can be more performant for large datasets since it doesn’t require storing all node values.

Test Cases

To effectively validate your solutions, consider creating comprehensive test cases, including edge cases:

  1. Empty Tree: root = None, k = 0
  2. Single Node: root = TreeNode(1), k = 2
  3. All Values Negative: Check how the function handles negative numbers.
  4. Large Balanced Tree: To test performance on larger inputs.

Conclusion

The "Two Sum IV - Input is a BST" problem is an excellent way to test your knowledge of binary search trees and algorithm efficiency. By using either the in-order traversal with a set or a pair of BST iterators, you can effectively find two numbers that add up to k.

Feel free to adapt the provided examples for your own practice, and don't hesitate to explore more about BST properties and traversal methods for a deeper understanding. Happy coding!

References

By providing detailed analysis, implementation examples, and discussing the pros and cons of various approaches, this article equips readers with a comprehensive understanding of solving this intriguing LeetCode problem.

Related Posts


Popular Posts