Skip to the code
+25 XP

#332 Pair of Prices for a Budget

medium

A gift-bundle feature wants to know whether two different products together cost exactly the shopper's budget. Prices are stored in a binary search tree with unique values.

Write hasPair(root, budget) that returns true if two different nodes have values that add up to budget, and false otherwise. A store can hold up to 100,000 prices, so checking every pair is far too slow. Aim for O(h) extra memory, where h is the tree's height.

Example 1

Input: root = [5,3,8,1,4,7,9], budget = 12
Output: true

3 + 9 = 12 (and 4 + 8 = 12).

Example 2

Input: root = [5,3,8,1,4,7,9], budget = 2
Output: false

The two cheapest prices already add up to 4.

Constraints

  • 0 <= number of prices <= 10^5
  • The tree is at most 3000 levels deep.
  • -10^5 <= price, budget <= 10^5

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).