1. Spend the Whole Gift Card

EasyJavaScriptStorefront

An online gift shop shows a "Spend it all" carousel on the checkout page when a customer pays with a gift card. Leftover balances annoy customers and create support tickets, so the shop suggests two different products whose prices add up to exactly the remaining balance.

The carousel loads up to a few thousand products and runs again every time the balance changes, so checking every pair with two nested loops is too slow on low-end phones.

Your task: Write findGiftCardPair(products, balance). Return the ids of the two products, in catalog order, or [] when no pair exists.

Rules: - products is a list of { id, price }. Prices and balance are in cents (positive integers). - The two products must be different entries. Two entries with the same price are fine. - A single product priced exactly at balance does not count. The carousel always shows a pair. - If several pairs work, return the pair whose second product appears earliest in the list. If there is still a tie, use the earliest first product.

Notes: - Aim for one pass over the list with a Map.

Examples

Example 1

Input
  • products = [
      { id: "mug", price: 1200 },
      { id: "socks", price: 800 },
      { id: "tote", price: 1800 },
      { id: "candle", price: 2000 }
    ]
  • balance = 3000
Output
  • ["mug", "tote"]
Explanation
1200 + 1800 = 3000. No other pair adds up to 3000.

Example 2

Input
  • products = [
      { id: "a", price: 1000 },
      { id: "b", price: 1000 },
      { id: "c", price: 2000 }
    ]
  • balance = 3000
Output
  • ["a", "c"]
Explanation
Both a and b pair with c. The pair completes at c either way, so the earliest partner (a) wins.

Solution

Write findGiftCardPair. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.

Test Results

Click "Run Code" to test your solution.