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
November 29, 20260
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
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- 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 ProblemsSample 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...