The Most Beautiful Item for Each Query problem gives you a list of items, each with a price and beauty rating, and a list of queries (each a price limit). For each query, find the maximum beauty among all items with price ≤ the query value. This Most Beautiful Item for Each Query coding problem combines sorting with binary search and prefix-max preprocessing.
Postmates, Amazon, and Google ask this because it tests a clean pattern: sort items by price, precompute a prefix-max beauty array, then binary search for each query. The array, sorting, and binary search interview pattern is directly applied, and the problem rewards candidates who preprocess before answering queries rather than scanning for each one.
Sort + prefix max + binary search. Sort items by price. Build a prefix-max beauty array where prefixMax[i] = maximum beauty among items[0..i]. For each query, binary search for the rightmost item with price ≤ query. Return prefixMax[found_index]. This achieves O((n+q) log n) total time.
Items: [(1,2), (3,5), (2,4), (5,6)]. Sort by price: [(1,2), (2,4), (3,5), (5,6)]. Prefix max: [2, 4, 5, 6]. Query 4: binary search finds last item with price ≤ 4 = index 2 (price=3). Max beauty = prefixMax[2] = 5. Query 1: last item with price ≤ 1 = index 0. Max beauty = 2.
"Best value within a price/capacity limit" problems follow a consistent pattern: sort by constraint, build prefix max/min of the objective, binary search per query. This approach applies to any problem with "find optimal value among all items meeting a threshold." After mastering this problem, practice extending it to 2D constraints (price + weight) where one dimension is sorted and the other uses a prefix structure.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Right Interval | Medium | Solve | |
| Sum of Mutated Array Closest to Target | Medium | Solve | |
| Magnetic Force Between Two Balls | Medium | Solve | |
| Find Target Indices After Sorting Array | Easy | Solve | |
| Special Array With X Elements Greater Than or Equal X | Easy | Solve |