2070. Most Beautiful Item for Each Query - Detailed Explanation
Problem Statement
Description:
You are given a 2D integer array items where each element items[i] = [price_i, beauty_i] represents an item with a certain price and its beauty value. You are also given an integer array queries, where each queries[j] is a price query. For each query, you must determine the maximum beauty of any item whose price is less than or equal to that query. If no such item exists, return 0 for that query.
Constraints:
- (1 \leq \text{items.length}, \text{queries.length} \leq 10^5)
- (1 \leq price_i, beauty_i, queries[j] \leq 10^9)
- The
itemsarray is not necessarily sorted.
Example 1:
- Input:
items = [[1,2],[3,2],[2,4],[5,6]]
queries = [1,2,3,4,5] - Output:
[2,4,4,4,6] - Explanation:
- For query = 1: Items with price ≤ 1 are ([[1,2]]) → maximum beauty = 2.
- For query = 2: Items with price ≤ 2 are ([[1,2], [2,4]]) → maximum beauty = 4.
- For query = 3: Items with price ≤ 3 are ([[1,2], [2,4], [3,2]]) → maximum beauty = 4.
- For query = 4: No new item added beyond price 3, so the answer remains 4.
- For query = 5: Items with price ≤ 5 are ([[1,2], [2,4], [3,2], [5,6]]) → maximum beauty = 6.
Example 2:
- Input:
items = [[1,2],[1,3],[2,4]]
queries = [1,2] - Output:
[3,4] - Explanation:
- For query = 1: Items with price ≤ 1 are ([[1,2],[1,3]]) → maximum beauty = max(2, 3) = 3.
- For query = 2: Items with price ≤ 2 are ([[1,2],[1,3],[2,4]]) → maximum beauty = 4.
Hints
- Hint 1: Sorting the
itemsarray by price helps quickly identify all items within a given query’s price limit. - Hint 2: Precompute a running (prefix) maximum of beauty values as you iterate through the sorted items.
- Hint 3: Process the queries in sorted order (while keeping track of their original indices) so you can use a two-pointer technique or binary search to efficiently answer each query.
Approaches
Approach 1: Brute Force
- Idea:
For each query, iterate over every item and check whether its price is within the query limit. Track the maximum beauty. - How It Works:
- For each query (q), loop over all items.
- If an item’s price ≤ (q), update the current maximum beauty.
- Drawback & Complexity:
- Time Complexity: (O(q \times n)), which is too slow when both arrays have up to (10^5) elements.
- Space Complexity: (O(1)) (ignoring output storage).
Approach 2: Two-Pointer Technique (Sorting Queries and Items)
- Idea:
Sort theitemsarray by price. Also, sort the queries along with their original indices. Then, use a two-pointer technique to traverse the sorted items and update a running maximum beauty. - How It Works:
- Sort Items:
Sortitemsin ascending order by price. - Sort Queries:
Pair each query with its original index and sort these pairs by the query value. - Two-Pointer Scan:
Initialize a pointer foritemsand a variablemaxBeautyto 0. For each query (in sorted order), advance the pointer while the item price is ≤ the query value. UpdatemaxBeautywith the highest beauty encountered so far. AssignmaxBeautyto the result corresponding to the query’s original index.
- Sort Items:
- Complexity:
- Time Complexity: (O(n \log n + q \log q + n + q)).
- Space Complexity: (O(n + q)).
Approach 3: Binary Search with Prefix Maximum
- Idea:
Sort theitemsarray by price and build a prefix array where each element is the maximum beauty up to that price. Then, for each query, use binary search to quickly find the appropriate prefix maximum. - How It Works:
-
Sort Items:
Sort by price. -
Build Prefix Maximum Array:
Create an arrayprefixBeautywhereprefixBeauty[i]is the maximum beauty among items from index 0 to (i). -
Answer Queries with Binary Search:
For each query, perform a binary search on the sorteditemsarray to find the largest index with price ≤ query, then return the corresponding value fromprefixBeauty.
-
- Complexity:
- Time Complexity: (O(n \log n + q \log n)).
- Space Complexity: (O(n + q)).
Python Code
Below is the Python implementation using the two-pointer technique:
Java Code
Below is the Java implementation using the two-pointer technique.
Complexity Analysis
- Time Complexity:
-
Sorting
itemstakes (O(n \log n)). -
Sorting the queries takes (O(q \log q)).
-
The two-pointer scanning step takes (O(n + q)).
-
Total: (O(n \log n + q \log q + n + q)).
-
- Space Complexity:
- (O(n + q)) for the sorted arrays and the result array.
Step-by-Step Walkthrough & Visual Example
Consider Example 1:
- Items:
[[1,2],[3,2],[2,4],[5,6]] - Queries:
[1,2,3,4,5]
-
Sort Items by Price:
Sorted items become:
[ [[1,2],; [2,4],; [3,2],; [5,6]] ] -
Sort Queries with Indices:
Sorted queries (with original indices):
[ [(1,0),; (2,1),; (3,2),; (4,3),; (5,4)] ] -
Process Queries in Order:
- Query = 1:
- Process items while (price \leq 1):
([1,2]) qualifies → updatemaxBeauty = 2. - Answer for original index 0 is 2.
- Process items while (price \leq 1):
- Query = 2:
- Continue: next item ([2,4]) qualifies (price 2 ≤ query 2) → update
maxBeauty = 4. - Answer for original index 1 is 4.
- Continue: next item ([2,4]) qualifies (price 2 ≤ query 2) → update
- Query = 3:
- Next item ([3,2]) qualifies (price 3 ≤ query 3); however,
maxBeautyremains 4. - Answer for original index 2 is 4.
- Next item ([3,2]) qualifies (price 3 ≤ query 3); however,
- Query = 4:
- No new item qualifies (price ≤ 4); answer remains 4 for index 3.
- Query = 5:
- Process next item ([5,6]) (price 5 ≤ query 5) → update
maxBeauty = 6. - Answer for original index 4 is 6.
- Process next item ([5,6]) (price 5 ≤ query 5) → update
- Query = 1:
-
Restore Original Order:
Final result array:[2, 4, 4, 4, 6].
Common Mistakes, Edge Cases & Alternative Variations
Common Mistakes:
- Not Sorting Queries:
Processing queries without sorting can complicate the two-pointer approach and lead to incorrect results. - Losing Original Query Order:
Failing to pair queries with their original indices may result in an output that does not match the input order. - Improper Pointer Movement:
Not correctly advancing the pointer foritemsmight lead to missing items that qualify for a later query.
Edge Cases:
-
No Valid Items:
If no item has a price ≤ a query, the answer for that query should be 0. -
Duplicate Prices with Different Beauties:
When multiple items share the same price, ensure that the maximum beauty among them is considered. -
Empty Items Array:
Although constrained, consider how the solution should behave ifitemsis empty.
Alternative Variations:
-
Online Queries:
If queries arrive one-by-one, data structures like segment trees or binary indexed trees might be used to answer queries dynamically. -
Extended Attributes:
A variant may involve more attributes (e.g., quality or rating) where you need to compute a combined metric.
Related Problems for Further Practice
GET YOUR FREE
Coding Questions Catalog
$197

$78
$78