2070. Most Beautiful Item for Each Query - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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 items array 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 items array 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 the items array 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:
    1. Sort Items:
      Sort items in ascending order by price.
    2. Sort Queries:
      Pair each query with its original index and sort these pairs by the query value.
    3. Two-Pointer Scan:
      Initialize a pointer for items and a variable maxBeauty to 0. For each query (in sorted order), advance the pointer while the item price is ≤ the query value. Update maxBeauty with the highest beauty encountered so far. Assign maxBeauty to the result corresponding to the query’s original index.
  • Complexity:
    • Time Complexity: (O(n \log n + q \log q + n + q)).
    • Space Complexity: (O(n + q)).
  • Idea:
    Sort the items array 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:
    1. Sort Items:
      Sort by price.

    2. Build Prefix Maximum Array:
      Create an array prefixBeauty where prefixBeauty[i] is the maximum beauty among items from index 0 to (i).

    3. Answer Queries with Binary Search:
      For each query, perform a binary search on the sorted items array to find the largest index with price ≤ query, then return the corresponding value from prefixBeauty.

  • 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:

Python3
Python3

. . . .

Java Code

Below is the Java implementation using the two-pointer technique.

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:
    • Sorting items takes (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]
  1. Sort Items by Price:
    Sorted items become:
    [ [[1,2],; [2,4],; [3,2],; [5,6]] ]

  2. Sort Queries with Indices:
    Sorted queries (with original indices):
    [ [(1,0),; (2,1),; (3,2),; (4,3),; (5,4)] ]

  3. Process Queries in Order:

    • Query = 1:
      • Process items while (price \leq 1):
        ([1,2]) qualifies → update maxBeauty = 2.
      • Answer for original index 0 is 2.
    • Query = 2:
      • Continue: next item ([2,4]) qualifies (price 2 ≤ query 2) → update maxBeauty = 4.
      • Answer for original index 1 is 4.
    • Query = 3:
      • Next item ([3,2]) qualifies (price 3 ≤ query 3); however, maxBeauty remains 4.
      • Answer for original index 2 is 4.
    • 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.
  4. 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 for items might 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 if items is 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.

TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How do you pass a technical assessment?
Are preparing JavaScript coding challenges on leetcode enough?
What is PCB in OS?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;