Most Beautiful Item for Each Query - Problem

You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.

You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.

Return an array answer of the same length as queries where answer[j] is the answer to the jth query.

Input & Output

Example 1 — Basic Case
$ Input: items = [[1,2],[3,2],[2,4]], queries = [1,2,3]
Output: [2,4,4]
💡 Note: Query 1: Only item [1,2] is affordable, beauty = 2. Query 2: Items [1,2] and [2,4] are affordable, max beauty = 4. Query 3: All items affordable, max beauty = 4.
Example 2 — No Affordable Items
$ Input: items = [[10,1000]], queries = [5]
Output: [0]
💡 Note: Query 5: The only item costs 10, which exceeds budget of 5, so return 0.
Example 3 — Multiple Queries
$ Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1,1]
Output: [4,4]
💡 Note: All items have price 1, so for budget 1, we can afford all items. Maximum beauty among all is 4.

Constraints

  • 1 ≤ items.length ≤ 105
  • 1 ≤ pricei, beautyi, queries[j] ≤ 109
  • 1 ≤ queries.length ≤ 105

Visualization

Tap to expand
Most Beautiful Item for Each Query INPUT items = [[price, beauty], ...] [1, 2] p=1, b=2 [3, 2] p=3, b=2 [2, 4] p=2, b=4 queries 1 2 3 Find max beauty where price <= query ALGORITHM STEPS 1 Sort items by price [1,2] --> [2,4] --> [3,2] 2 Track max beauty Update running max at each price Price: 1 --> maxB: 2 Price: 2 --> maxB: max(2,4)=4 Price: 3 --> maxB: max(4,2)=4 Result: [[1,2],[2,4],[3,4]] 3 Sort queries with index [(1,0), (2,1), (3,2)] 4 Binary search / Two pointer Find max beauty for each query q=1: price<=1 --> max=2 q=2: price<=2 --> max=4 q=3: price<=3 --> max=4 FINAL RESULT Query Results Mapping q=1 2 q=2 4 q=3 4 Output Array [2, 4, 4] OK - Verified Key Insight: By sorting items by price and maintaining a running maximum of beauty, we can efficiently answer queries. For each price point, we track the best beauty seen so far. This allows binary search or two-pointer approach for O(n log n + m log m) time complexity. TutorialsPoint - Most Beautiful Item for Each Query | Optimal Solution
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
34.5K Views
High Frequency
~25 min Avg. Time
967 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen