Two Ad Bids in a BST Summing to the Target Spend

Last updated: November 29, 2026

Quick Overview

Given a BST of distinct bid amounts and a target, return whether two different nodes sum to the target, using O(h) extra memory.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given a BST of distinct bid amounts and a target, return whether two different nodes sum to the target, using O(h) extra memory.

A Meta phone-screen question that starts with the hash-set answer and then asks for O(h) memory. The interviewer wants to see two BST iterators moving toward each other, the tree version of two pointers on a sorted array.

What the Interviewer Expects
  • Offer the O(n) hash-set traversal first
  • Recognize the sorted-order two-pointer approach
  • Build ascending and descending iterators with stacks
  • Stop when the iterators meet
  • State O(n) time, O(h) memory
Key Topics to Cover
BST
two pointers
iterators
hash set
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if the two values come from two different BSTs?
  • Return all pairs that hit the target.
  • Count pairs whose sum is at most the target.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: BST root (distinct values), integer target.
  • Output: True if two distinct nodes have values summing to target.
  • Memory target: O(h)....
High-Level Design

Baseline: traverse and keep a set of seen values; check target - v per node. O(n) time and O(n) memory.

To get O(h) memory, use the sorted order. On a sorted array we would move a left pointer up a...


Submit Your Answer
Markdown supported