Skip to main content

Most Beautiful Item for Each Query - Solution & Explanation

MediumArrayBinary SearchSorting27 min readAsked at: Amazon, Google, Razorpay +1
Practice this problem

Problem Statement

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.

 

Example 1:

Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. 
  The maximum beauty among them is 4.
- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
  The maximum beauty among them is 5.
- For queries[4]=5 and queries[5]=6, all items can be considered.
  Hence, the answer for them is the maximum beauty of all items, i.e., 6.

Example 2:

Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation: 
The price of every item is equal to 1, so we choose the item with the maximum beauty 4. 
Note that multiple items can have the same price and/or beauty.  

Example 3:

Input: items = [[10,1000]], queries = [5]
Output: [0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen.
Hence, the answer to the query is 0.

 

Constraints:

  • 1 <= items.length, queries.length <= 105
  • items[i].length == 2
  • 1 <= pricei, beautyi, queries[j] <= 109

Approach Overview

Problem Overview: You are given items where each item has a price and beauty, and a list of queries representing the maximum price you can pay. For each query, return the maximum beauty among all items with price ≤ query. The challenge is answering many queries efficiently without scanning the entire list every time.

Approach 1: Sort and Binary Search Approach (O((n + q) log n) time, O(n) space)

Sort the items by price. After sorting, build a prefix array where each position stores the maximum beauty seen so far up to that price. This transforms the problem into a monotonic lookup: if you know the largest index whose price is ≤ query, the prefix value already contains the best beauty available.

For every query, run a binary search on the sorted price list to find the rightmost item whose price does not exceed the query value. Return the prefix maximum beauty at that index. Sorting costs O(n log n), and each query takes O(log n), making the full solution O((n + q) log n). The additional space is O(n) for storing prefix maximum values.

This method relies heavily on sorting and binary search. Once the prefix maximum array is built, each query becomes a simple lookup after the search.

Approach 2: Coordinate Compression and Dynamic Programming (O((n + q) log n) time, O(n) space)

Prices can be large and sparse. Coordinate compression maps all unique prices from items and queries into a compact index range. After compression, create a DP array where dp[i] represents the maximum beauty achievable for any price index ≤ i.

First record the maximum beauty for each compressed price from the item list. Then build the DP array using a prefix maximum scan so that every index inherits the best beauty seen so far. For each query, convert its price to the corresponding compressed index (using binary search on the compressed list) and read the DP value directly.

This approach also runs in O((n + q) log n) due to sorting during compression and binary search for query mapping, while the DP prefix pass is linear. Space usage remains O(n). It works well when you want explicit control over price indexing or when integrating with other array-based dynamic programming structures.

Recommended for interviews: The sort + binary search solution is what interviewers typically expect. It demonstrates understanding of preprocessing with prefix maximums and efficient query handling using binary search. The coordinate compression variant shows deeper algorithmic thinking but is rarely required unless the constraints demand more structured indexing.

Approach 1: Sort and Binary Search Approach

In this approach, we perform the following steps:

  • Sort the items based on their price. If two items have the same price, sort by beauty.
  • Next, traverse through the sorted items and keep track of the maximum beauty encountered so far.
  • Store each price and corresponding maximum beauty in a new list.
  • For each query, binary search this list to find the maximum beauty for the given budget.

The algorithm first sorts the items based on their price. While traversing through the sorted list, it maintains the maximum beauty for each price. For each query, a binary search is executed on this list of prices to fetch the corresponding maximum beauty. This method ensures optimal handling of both items and queries given constraints.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O((n + m) log n) where n = number of items and m = number of queries.
Space Complexity: O(n) for storing the processed items data.

Try this approach in the editor →

Approach 2: Coordinate Compression and Dynamic Programming

Coordinate compression can be used to reduce problem complexity when dealing with large range values like prices. In this approach:

  • First compress the prices of items to a manageable index set.
  • Using this index set, prepare a dynamic programming list indicating the maximum beauty available at each index.
  • Through the compressed indices, iterate to build a cumulative beauty list.
  • Finally, with the queries represented in terms of these compressed indices, gather answers by simple lookups in this list.

This solution first compresses the range of prices into indexes, reducing the search space. A dynamic programming approach then determines the maximum beauty at each possible price point index, allowing quick lookup when answering queries. This methodology deals efficiently with large query ranges.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O((n + m) log(n + m)) due to sorting during compression.
Space Complexity: O(n + m) for storing all price points and decision arrays.

Try this approach in the editor →

Approach 3: Sorting + Offline Query

For each query, we need to find the maximum beauty value among the items with a price less than or equal to the query price. We can use the offline query method, first sort the items by price, and then sort the queries by price.

Next, we traverse the queries from small to large. For each query, we use a pointer i to point to the item array. If the price of the item is less than or equal to the query price, we update the current maximum beauty value and move the pointer i to the right until the price of the item is greater than the query price. We record the current maximum beauty value, which is the answer to the current query. Continue to traverse the next query until all queries are processed.

The time complexity is O(n times log n + m times log m), and the space complexity is O(log n + m). Where n and m are the lengths of the item array and the query array, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 4: Sorting + Binary Search

We can sort the items by price, and then preprocess the maximum beauty value of the items that are less than or equal to each price, recorded in the array mx or the original items array.

For each query, we can use binary search to find the index j of the first item with a price greater than the query price, then j - 1 is the index of the item with the maximum beauty value and a price less than or equal to the query price, which is added to the answer.

The time complexity is O((m + n) times log n), and the space complexity is O(n). Where n and m are the lengths of the item array and the query array, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sort and Binary Search Approach

Time Complexity: O((n + m) log n) where n = number of items and m = number of queries.
Space Complexity: O(n) for storing the processed items data.

Coordinate Compression and Dynamic Programming

Time Complexity: O((n + m) log(n + m)) due to sorting during compression.
Space Complexity: O(n + m) for storing all price points and decision arrays.

Sorting + Offline Query
Sorting + Binary Search

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sort + Prefix Max + Binary SearchO((n + q) log n)O(n)Best general solution when handling many queries on price limits
Coordinate Compression + Dynamic ProgrammingO((n + q) log n)O(n)Useful when prices are large or sparse and you want compact indexed DP

Video Solution

Most Beautiful Item for Each Query | Simple Explanation | Leetcode 2070 | codestorywithMIKcodestorywithMIK9,474 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Most Beautiful Item for Each Query easy or hard?
Most Beautiful Item for Each Query is classified as a Medium difficulty problem. The core idea—sorting and using prefix maximums—is straightforward, but recognizing how to answer multiple queries efficiently with binary search requires some algorithmic experience.
Most Beautiful Item for Each Query Python/Java solution
In Python or Java, the common implementation sorts the items by price, builds a prefix maximum beauty array, and uses binary search for each query. Libraries like bisect in Python or Arrays.binarySearch in Java help locate the correct price index quickly.
How to solve Most Beautiful Item for Each Query in O(n)?
A strict O(n) solution is generally not feasible because queries require searching across sorted prices. The closest efficient approach preprocesses items using sorting and prefix maximums, then answers each query with binary search. This results in O((n + q) log n) time overall.
What is the best approach for Most Beautiful Item for Each Query?
The most efficient approach sorts items by price and builds a prefix array storing the maximum beauty seen so far. Each query then uses binary search to find the most expensive item within the price limit. This reduces repeated scanning and runs in O((n + q) log n) time with O(n) space.
Is Most Beautiful Item for Each Query asked at Google/Amazon/Meta?
Problems combining sorting, prefix maximum preprocessing, and binary search are common in interviews at companies like Amazon, Google, and Meta. Variations of range query optimization and price filtering frequently appear in technical interviews.
What data structure is used in Most Beautiful Item for Each Query?
The solution mainly uses arrays combined with sorting and binary search. A prefix maximum array stores the best beauty seen up to each price. Some implementations also use coordinate compression with dynamic programming arrays for efficient indexing.
What is the time complexity of Most Beautiful Item for Each Query?
The optimal solution runs in O((n + q) log n) time. Sorting the items takes O(n log n), and each query is answered using binary search in O(log n). Space complexity is O(n) for storing prefix maximum beauty values.

Ready to solve this problem?

Practice Most Beautiful Item for Each Query with our built-in code editor and test cases.

Practice on FleetCode