Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Two Sum IV - Input is a BST

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "653" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise. Example 1: Input: root = [5,3,6,2,4,null,7], k = 9 Output: true Example 2: Input: root = [5,3,6,2,4,null,7], k = 28 Output: false Constraints: The number of nodes in the tree is in the range [1, 104]. -104 <= Node.val <= 104 root is guaranteed to be a valid binary search tree. -105 <= k <= 105

Explanation

Here's an efficient solution to determine if there exist two elements in a BST that sum to a target value k.

  • Inorder Traversal: Perform an inorder traversal of the BST to obtain a sorted list of the node values.
  • Two-Pointer Approach: Use the two-pointer technique on the sorted list to efficiently search for two numbers that sum up to k. One pointer starts at the beginning of the list, and the other starts at the end.
  • Optimization: The two-pointer approach is particularly efficient since the array is sorted, allowing us to move pointers inwards based on whether the current sum is greater or less than the target.

  • Runtime Complexity: O(N), where N is the number of nodes in the BST. Storage Complexity: O(N) due to storing the inorder traversal in a list.

Code

    from typing import Optional, List

# Definition for a binary tree node.
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: Optional[TreeNode], k: int) -> bool:
        """
        Given the root of a binary search tree and an integer k,
        return true if there exist two elements in the BST such that their sum is equal to k,
        or false otherwise.
        """

        nums: List[int] = []

        def inorder(node: Optional[TreeNode]):
            if not node:
                return
            inorder(node.left)
            nums.append(node.val)
            inorder(node.right)

        inorder(root)

        left, right = 0, len(nums) - 1
        while left < right:
            current_sum = nums[left] + nums[right]
            if current_sum == k:
                return True
            elif current_sum < k:
                left += 1
            else:
                right -= 1

        return False

More from this blog

C

Chatmagic blog

2894 posts