Maximize products bought under budget
Company: TikTok
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic problem-solving skills including sorting, prefix-sum accumulation, binary search, greedy selection, careful tie-breaking for lexicographic order, and complexity analysis.
Constraints
- 1 <= len(products), len(customers) <= 200000
- 0 <= price, budget <= 1000000000
- product_id values are distinct integers
- Ties on product price are broken by smaller product_id
- The total number of returned product IDs may be large; output construction cost is counted separately from per-customer query time
Examples
Input: ([(1, 100), (2, 100), (3, 300), (4, 500)], [(10, 500)])
Expected Output: [(10, 3, [1, 2, 3])]
Explanation: The three cheapest products cost 100 + 100 + 300 = 500, so customer 10 can buy 3 products.
Input: ([(5, 10), (2, 20)], [(1, 9)])
Expected Output: [(1, 0, [])]
Explanation: The customer's budget is smaller than the cheapest product price, so no products can be bought.
Input: ([(3, 5), (1, 0), (2, 5)], [(7, 10)])
Expected Output: [(7, 3, [1, 2, 3])]
Explanation: Sorted by price then product_id, the products are 1, 2, 3 with total cost 10, so all products are chosen.
Input: ([(5, 2), (1, 2), (3, 2), (4, 5)], [(8, 4)])
Expected Output: [(8, 2, [1, 3])]
Explanation: Any two price-2 products maximize the count with spend 4. The tie is broken by smaller product_id, so products 1 and 3 are chosen.
Input: ([(10, 8), (20, 3), (30, 3), (40, 2), (50, 10)], [(1, 1), (2, 5), (3, 15), (4, 100)])
Expected Output: [(1, 0, []), (2, 2, [40, 20]), (3, 3, [40, 20, 30]), (4, 5, [40, 20, 30, 10, 50])]
Explanation: Products sorted by price then product_id are [40, 20, 30, 10, 50] with prefix costs [2, 5, 8, 16, 26]. Each budget chooses the longest affordable prefix.
Input: ([(7, 0), (2, 0), (5, 1)], [(9, 0), (10, 1)])
Expected Output: [(9, 2, [2, 7]), (10, 3, [2, 7, 5])]
Explanation: A zero budget can still buy all zero-price products. Equal zero prices are ordered by product_id.
Hints
- For any fixed count k, the cheapest possible way to buy k products is to take the first k products after sorting by price, then product_id.
- Build prefix sums of the sorted prices. For a customer budget B, binary search for the largest k such that prefix_sums[k] <= B.