Magicsheet logo

Most Beautiful Item for Each Query

Medium
98.1%
Updated 6/1/2025

Most Beautiful Item for Each Query

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

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.

Common mistakes candidates make

  • Not building the prefix max (searching for max in range for each query is O(n) per query).
  • Binary searching on unsorted items (must sort by price first).
  • Returning raw beauty at the found index instead of the prefix-max.
  • Not handling the case where no item's price ≤ query (return 0).

Interview preparation tip

"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.

Similar Questions