Online store~25 min2s · 256 MBtarget O(n^2) time, O(n) spaceclassic twin: lc-15k-sum · two-pointers · sorting
An online store sells gift cards of a fixed value. Your team lead wants a "spend it exactly" feature. It suggests three different catalogue items whose prices add up to exactly the card's value, so nothing is left on the card.
Before launch, the merchandising team wants every distinct price combination for a given value. Prices are integers in minor units, and several items can share a price. So two different sets of items can give the same three prices. The team wants each combination of prices once.
Write price_triples(prices, value).
prices[i] is the price of item i in minor units. The list is in no particular order and may hold equal prices.value is the gift card's value in minor units.[a, b, c] with a ≤ b ≤ c and a + b + c == value, where the three prices come from three different positions.prices, and no more.a first, then b, then c.[].Input: prices = [4500, 1500, 3000, 1500, 2000, 2500], value = 7500
Output: [[1500, 1500, 4500], [2000, 2500, 3000]]Sorted, the prices are [1500, 1500, 2000, 2500, 3000, 4500]. The trace works on that sorted copy.
| i | First price | Rest | left | right | Pair total | Compared with rest | Move |
|---|---|---|---|---|---|---|---|
| 0 | 1500 | 6000 | 1 | 5 | 1500 + 4500 = 6000 | exact | record [1500, 1500, 4500]; both move |
| 0 | 1500 | 6000 | 2 | 4 | 2000 + 3000 = 5000 | too small | left becomes 3 |
| 0 | 1500 | 6000 | 3 | 4 | 2500 + 3000 = 5500 | too small | left becomes 4: the pointers meet |
| 1 | 1500 | same as the price before | skip | ||||
| 2 | 2000 | 5500 | 3 | 5 | 2500 + 4500 = 7000 | too large | right becomes 4 |
| 2 | 2000 | 5500 | 3 | 4 | 2500 + 3000 = 5500 | exact | record [2000, 2500, 3000]; both move |
| 3 | 2500 | 5000 | 4 | 5 | 3000 + 4500 = 7500 | too large | right becomes 4: the pointers meet |
The price 1500 appears twice, so [1500, 1500, 4500] is allowed. The second 1500 as a first price would only repeat that triple, so it is skipped.
Input: prices = [2500, 2500, 2500, 2500, 2500], value = 7500
Output: [[2500, 2500, 2500]]There are 10 ways to choose three of the five items, and every way matches. They all give the same three prices, so the answer holds one triple.
Input: prices = [1000, 2000, 4000, 8000], value = 6000
Output: []The possible totals are 7000, 11000, 13000 and 14000. None of them is 6000.
1 ≤ prices.length ≤ 3,000 (the items in one gift catalogue)1 ≤ prices[i] ≤ 10^73 ≤ value ≤ 3 × 10^7Trying every triple of items costs n × (n − 1) × (n − 2) / 6 checks. At n = 3,000 that is 4,495,501,000, about 4.5 × 10^9: far over the budget of about 10^8 simple operations a second. An O(n^2) solution makes about 4.5 × 10^6 steps, which fits easily.
Read the values too. The largest total is 3 × 10^7, far below the 32-bit limit of 2,147,483,647, so int is safe in every language.