Find Two Catalog Prices in a Search Tree That Hit a Budget

Last updated: November 29, 2026

Quick Overview

Given a binary search tree of item prices and a gift card balance, return True if two different items have prices that sum exactly to the balance. Aim for O(h) extra space.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given a binary search tree of item prices and a gift card balance, return True if two different items have prices that sum exactly to the balance. Aim for O(h) extra space.

An Amazon onsite variant of two-sum that tests whether you can use the BST as a sorted sequence without copying it. A strong answer builds forward and backward iterators and explains the space win over a hash set.

What the Interviewer Expects
  • Give the hash-set baseline first: O(n) time and O(n) space
  • Recognize that an inorder traversal is sorted and enables two pointers
  • Implement ascending and descending iterators backed by stacks
  • Stop when the two iterators meet
  • Analyze O(n) time and O(h) space
Key Topics to Cover
BST
two pointers
BST iterator
stacks
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
  • How would you count all such pairs instead of returning a boolean?
  • What if you needed the pair closest to the balance without exceeding it?
  • How would this change if the tree were too large for memory and stored on disk?
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 with unique integer prices and an integer target. Output: True if two distinct nodes sum to target. The same node cannot be used twice....

High-Level Design

Two pointers on a sorted array is the classic O(1)-space approach; the BST equivalent uses two lazy iterators. The low iterator pushes the leftmost path and yields nodes in ascending order; the high i...


Submit Your Answer
Markdown supported