Talentd
FleetCode
Make and follow sheets.Sign in

Most Beautiful Item for Each Query solution and explanation

MediumArrayBinary SearchSorting8 min read62.2% acceptanceUpdated 9 Apr 2026
Most Beautiful Item for Each Query | Simple Explanation | Leetcode 2070 | codestorywithMIKcodestorywithMIK · 22:44 · 9K viewsWatch on YouTube
9 more videos on this problem
  1. Most Beautiful Item for Each Query | Simple Explanation | Leetcode 2070 | codestorywithMIKcodestorywithMIK · 22:44 · 9K views
  2. Most Beautiful Item for Each Query - Leetcode 2070 - PythonNeetCodeIO · 17:17 · 8K views
  3. Most Beautiful Item for Each Query | Leetcode 2070Techdose · 11:35 · 2K views
  4. 2070. Most Beautiful Item for Each Query | Binary Search | Prefix Sums | Static Queries - 2 PointersAryan Mittal · 19:03 · 2K views
  5. 2070. Most Beautiful Item for Each Query | Leetcode Biweekly Contest 65 | Binary Search | DSATejpratap Pandey · 23:27 · 751 views
  6. 2070. Most Beautiful Item for Each Query (Leetcode Medium)Programming Live with Larry · 13:16 · 608 views
  7. Daily Leetcode #1687: Nov 12, 2024 - 2070. Most Beautiful Item for Each QueryProgramming Live with Larry · 14:32 · 372 views
  8. 2070. Most Beautiful Item for Each Query | Binary Search | Sorting | Leetcode Daily Challenge | JAVALeetQuest · 13:02 · 111 views
  9. 2070 Most Beautiful Item for Each Query - Day 12/30 Leetcode November - Python - Simple ExplanationImagination To Code · 18:04 · 108 views
  10. Most beautiful item for each query | Leetcode 2070 | Sorting 🔥🔥Code With Amit · 9:12 · 88 views

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

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.
def maxBeautyForQueries(items, queries):
    items = sorted(items)
    max_beauty = [0] * len(items)
    current_max = 0

    for i, (price, beauty) in enumerate(items):
        current_max = max(current_max, beauty)
        max_beauty[i] = current_max

    def findBest(query):
        left, right = 0, len(items) - 1
        while left <= right:
            mid = (left + right) // 2
            if items[mid][0] <= query:
                left = mid + 1
            else:
                right = mid - 1
        return max_beauty[right] if right >= 0 else 0

    return [findBest(q) for q in queries]

# Example usage
items = [[1,2],[3,2],[2,4],[5,6],[3,5]]
queries = [1,2,3,4,5,6]
print(maxBeautyForQueries(items, queries))
import java.util.*;

class Solution {
    public int[] maxBeautyForQueries(int[][] items, int[] queries) {
        Arrays.sort(items, (a, b) -> a[0] - b[0]);
        int[] maxBeauties = new int[items.length];
        int maxBeauty = 0;

        for (int i = 0; i < items.length; i++) {
            maxBeauty = Math.max(maxBeauty, items[i][1]);
            maxBeauties[i] = maxBeauty;
        }

        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int idx = Arrays.binarySearch(items, new int[]{queries[i], Integer.MAX_VALUE}, Comparator.comparingInt(a -> a[0]));
            if (idx < 0) idx = -idx - 2;
            result[i] = idx >= 0 ? maxBeauties[idx] : 0;
        }

        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[][] items = {{1,2}, {3,2}, {2,4}, {5,6}, {3,5}};
        int[] queries = {1, 2, 3, 4, 5, 6};
        int[] result = sol.maxBeautyForQueries(items, queries);
        System.out.println(Arrays.toString(result));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> maxBeautyForQueries(vector<pair<int, int>>& items, vector<int>& queries) {
    sort(items.begin(), items.end());
    vector<int> maxBeauty;
    int currentMax = 0; for (const auto& item : items) {
        currentMax = max(currentMax, item.second);
        maxBeauty.push_back(currentMax);
    }

    vector<int> answer(queries.size());
    for (size_t i = 0; i < queries.size(); ++i) {
        int idx = upper_bound(items.begin(), items.end(), make_pair(queries[i], INT_MAX)) - items.begin() - 1;
        answer[i] = (idx >= 0) ? maxBeauty[idx] : 0;
    }
    return answer;
}

int main() {
    vector<pair<int, int>> items = {{1,2},{3,2},{2,4},{5,6},{3,5}};
    vector<int> queries = {1, 2, 3, 4, 5, 6};
    vector<int> result = maxBeautyForQueries(items, queries);
    for (int res : result) {
        cout << res << " ";
    }
    return 0;
}
function maxBeautyForQueries(items, queries) {
    items.sort((a, b) => a[0] - b[0]);
    const maxBeauty = new Array(items.length);
    let maxB = 0;

    for (let i = 0; i < items.length; i++) {
        maxB = Math.max(maxB, items[i][1]);
        maxBeauty[i] = maxB;
    }

    function findBest(query) {
        let left = 0, right = items.length - 1;
        while (left <= right) {
            const mid = Math.floor((left + right) / 2);
            if (items[mid][0] <= query) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return right >= 0 ? maxBeauty[right] : 0;
    }

    return queries.map(findBest);
}

// Example usage:
const items = [[1,2],[3,2],[2,4],[5,6],[3,5]];
const queries = [1,2,3,4,5,6];
console.log(maxBeautyForQueries(items, queries));
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    int *item1 = *(int **)a;
    int *item2 = *(int **)b;
    if (item1[0] == item2[0]) return item2[1] - item1[1];
    return item1[0] - item2[0];
}

int binarySearch(int *prices, int *beauties, int left, int right, int query) {
    int answer = 0;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (prices[mid] <= query) {
            answer = beauties[mid];
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return answer;
}

int* maxBeautyForQueries(int **items, int itemsSize, int *itemsColSize, int *queries, int queriesSize, int *returnSize) {
    qsort(items, itemsSize, sizeof(int *), compare);
    int *prices = (int *)malloc(sizeof(int) * itemsSize);
    int *beauties = (int *)malloc(sizeof(int) * itemsSize);
    int currentMaxBeauty = 0;

    for (int i = 0; i < itemsSize; i++) {
        currentMaxBeauty = currentMaxBeauty > items[i][1] ? currentMaxBeauty : items[i][1];
        prices[i] = items[i][0];
        beauties[i] = currentMaxBeauty;
    }

    int *result = (int *)malloc(sizeof(int) * queriesSize);
    for (int i = 0; i < queriesSize; i++) {
        result[i] = binarySearch(prices, beauties, 0, itemsSize - 1, queries[i]);
    }

    free(prices);
    free(beauties);
    *returnSize = queriesSize;
    return result;
}

int main() {
    int *items[] = { (int[]){1, 2}, (int[]){3, 2}, (int[]){2, 4}, (int[]){5, 6}, (int[]){3, 5} };
    int queries[] = {1, 2, 3, 4, 5, 6};
    int itemsSize = 5;
    int queriesSize = 6;
    int itemsColSize = 2;
    int returnSize;
    int *result = maxBeautyForQueries(items, itemsSize, &itemsColSize, queries, queriesSize, &returnSize);
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", result[i]);
    }
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int[] MaxBeautyForQueries(int[][] items, int[] queries) {
        Array.Sort(items, (a, b) => a[0] - b[0]);
        int[] maxBeauties = new int[items.Length];
        int maxBeauty = 0;

        for (int i = 0; i < items.Length; i++) {
            maxBeauty = Math.Max(maxBeauty, items[i][1]);
            maxBeauties[i] = maxBeauty;
        }

        int[] result = new int[queries.Length];
        for (int i = 0; i < queries.Length; i++) {
            int idx = Array.BinarySearch(items, new int[]{queries[i], int.MaxValue}, Comparer<int[]>.Create((a, b) => a[0] - b[0]));
            if (idx < 0) idx = ~idx - 1;
            result[i] = idx >= 0 ? maxBeauties[idx] : 0;
        }
        return result;
    }

    public static void Main(string[] args) {
        var solution = new Solution();
        int[][] items = new int[][] { new int[] {1,2}, new int[] {3,2}, new int[] {2,4}, new int[] {5,6}, new int[] {3,5} };
        int[] queries = new int[] { 1, 2, 3, 4, 5, 6 };
        int[] result = solution.MaxBeautyForQueries(items, queries);
        Console.WriteLine(string.Join(" ", result));
    }
}

Python handles the sorted list of items by computing a cumulative record of the best beauty seen by iterating. Then, it directly applies binary search per query, making it extremely fast especially with large datasets.

Complexity

Time Complexity: O((n + m) log n) due to efficient sorting and searching.
Space Complexity: O(n) for tracking maximum beauties.

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.
def maxBeautyWithCompression(items, queries):
    from bisect import bisect_right

    allPrices = sorted({item[0] for item in items}.union(queries))
    dp = {price: 0 for price in allPrices}

    for price, beauty in items:
        dp[price] = max(dp[price], beauty)

    current_max = 0
    for price in allPrices:
        current_max = max(current_max, dp[price])
        dp[price] = current_max

    return [dp[allPrices[bisect_right(allPrices, q) - 1]] for q in queries if bisect_right(allPrices, q) > 0 else 0]

# Example usage
items = [[1,2],[3,2],[2,4],[5,6],[3,5]]
queries = [1,2,3,4,5,6]
print(maxBeautyWithCompression(items, queries))
import java.util.*;

class Solution {
    public int[] maxBeautyWithCompression(int[][] items, int[] queries) {
        TreeSet<Integer> priceSet = new TreeSet<>();
        for (int[] item : items) priceSet.add(item[0]);
        for (int query : queries) priceSet.add(query);
        Integer[] priceArray = priceSet.toArray(new Integer[0]);
        Map<Integer, Integer> compressMap = new HashMap<>();
        for (int i = 0; i < priceArray.length; i++) compressMap.put(priceArray[i], i);

        int[] dp = new int[priceArray.length];
        for (int[] item : items) {
            int idx = compressMap.get(item[0]);
            dp[idx] = Math.max(dp[idx], item[1]);
        }

        for (int i = 1; i < dp.length; i++) {
            dp[i] = Math.max(dp[i], dp[i - 1]);
        }

        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int idx = Arrays.binarySearch(priceArray, queries[i]);
            if (idx < 0) idx = -idx - 2;
            result[i] = idx >= 0 ? dp[idx] : 0;
        }

        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[][] items = {{1,2}, {3,2}, {2,4}, {5,6}, {3,5}};
        int[] queries = {1, 2, 3, 4, 5, 6};
        int[] result = sol.maxBeautyWithCompression(items, queries);
        System.out.println(Arrays.toString(result));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

vector<int> maxBeautyWithCompression(vector<pair<int, int>>& items, vector<int>& queries) {
    vector<int> allPrices;
    unordered_map<int, int> compressMap;
    for (const auto& item : items) allPrices.push_back(item.first);
    for (const int& query : queries) allPrices.push_back(query);
    sort(allPrices.begin(), allPrices.end());
    allPrices.erase(unique(allPrices.begin(), allPrices.end()), allPrices.end());

    vector<int> dp(allPrices.size(), 0);
    for (const auto& item : items) {
        int index = lower_bound(allPrices.begin(), allPrices.end(), item.first) - allPrices.begin();
        dp[index] = max(dp[index], item.second);
    }

    for (int i = 1; i < dp.size(); ++i) {
        dp[i] = max(dp[i], dp[i - 1]);
    }

    vector<int> result;
    for (const int& query : queries) {
        int index = upper_bound(allPrices.begin(), allPrices.end(), query) - allPrices.begin() - 1;
        result.push_back(index >= 0 ? dp[index] : 0);
    }

    return result;
}

int main() {
    vector<pair<int, int>> items = {{1,2},{3,2},{2,4},{5,6},{3,5}};
    vector<int> queries = {1, 2, 3, 4, 5, 6};
    vector<int> result = maxBeautyWithCompression(items, queries);
    for (int res : result) {
        cout << res << " ";
    }
    return 0;
}
function maxBeautyWithCompression(items, queries) {
    const allPrices = Array.from(new Set(items.map(x => x[0]).concat(queries))).sort((a, b) => a - b);
    const dp = new Map(); allPrices.forEach(price => dp.set(price, 0));

    for (const [price, beauty] of items) {
        dp.set(price, Math.max(dp.get(price), beauty));
    }

    let currentMax = 0;
    allPrices.forEach(price => {
        currentMax = Math.max(currentMax, dp.get(price));
        dp.set(price, currentMax);
    });

    return queries.map(query => {
        const index = allPrices.findIndex(price => price > query) - 1;
        return index >= 0 ? dp.get(allPrices[index]) : 0;
    });
}

// Example usage:
const items = [[1,2],[3,2],[2,4],[5,6],[3,5]];
const queries = [1,2,3,4,5,6];
console.log(maxBeautyWithCompression(items, queries));
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int *)a) - (*(int *)b);
}

int* coordinateCompress(int *values, int size, int *newSize) {
    int *sortedValues = (int *)malloc(sizeof(int) * size);
    for (int i = 0; i < size; i++) sortedValues[i] = values[i];
    qsort(sortedValues, size, sizeof(int), compare);

    int *compressedValues = (int *)malloc(sizeof(int) * size);
    int last = -1;
    *newSize = 0;
    for (int i = 0; i < size; i++) {
        if (i == 0 || sortedValues[i] != last) {
            compressedValues[(*newSize)++] = sortedValues[i];
            last = sortedValues[i];
        }
    }
    free(sortedValues);
    return compressedValues;
}

int findIndex(int *arr, int size, int value) {
    int left = 0, right = size - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] <= value) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return right;
}

int* maxBeautyWithCompression(int **items, int itemsSize, int *itemsColSize, int *queries, int queriesSize, int *returnSize) {
    int *allPrices = (int *)malloc(sizeof(int) * (itemsSize + queriesSize));
    for (int i = 0; i < itemsSize; i++) allPrices[i] = items[i][0];
    for (int i = 0; i < queriesSize; i++) allPrices[itemsSize + i] = queries[i];

    int newPricesSize;
    int *compressedPrices = coordinateCompress(allPrices, itemsSize + queriesSize, &newPricesSize);

    int *dp = (int *)calloc(newPricesSize, sizeof(int));
    for (int i = 0; i < itemsSize; i++) {
        int idx = findIndex(compressedPrices, newPricesSize, items[i][0]);
        if (dp[idx] < items[i][1]) {
            dp[idx] = items[i][1];
        }
    }

    for (int i = 1; i < newPricesSize; i++) {
        if (dp[i] < dp[i - 1]) {
            dp[i] = dp[i - 1];
        }
    }

    int *result = (int *)malloc(sizeof(int) * queriesSize);
    for (int i = 0; i < queriesSize; i++) {
        int idx = findIndex(compressedPrices, newPricesSize, queries[i]);
        result[i] = idx >= 0 ? dp[idx] : 0;
    }

    free(allPrices);
    free(compressedPrices);
    free(dp);
    *returnSize = queriesSize;
    return result;
}

int main() {
    int *items[] = { (int[]){1, 2}, (int[]){3, 2}, (int[]){2, 4}, (int[]){5, 6}, (int[]){3, 5} };
    int queries[] = {1, 2, 3, 4, 5, 6};
    int itemsSize = 5;
    int queriesSize = 6;
    int itemsColSize = 2;
    int returnSize;
    int *result = maxBeautyWithCompression(items, itemsSize, &itemsColSize, queries, queriesSize, &returnSize);
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", result[i]);
    }
    free(result);
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int[] MaxBeautyWithCompression(int[][] items, int[] queries) {
        var priceSet = new SortedSet<int>();
        foreach (var item in items) priceSet.Add(item[0]);
        foreach (var query in queries) priceSet.Add(query);

        var prices = new List<int>(priceSet);
        var dp = new Dictionary<int, int>();
        foreach (var price in prices) dp[price] = 0;

        foreach (var item in items) {
            dp[item[0]] = Math.Max(dp[item[0]], item[1]);
        }

        int currentMax = 0;
        foreach (var price in prices) {
            currentMax = Math.Max(currentMax, dp[price]);
            dp[price] = currentMax;
        }

        var result = new int[queries.Length];
        for (int i = 0; i < queries.Length; i++) {
            var index = prices.BinarySearch(queries[i]);
            if (index < 0) index = ~index - 1;
            result[i] = index >= 0 ? dp[prices[index]] : 0;
        }

        return result;
    }

    public static void Main(string[] args) {
        var solution = new Solution();
        int[][] items = new int[][] { new int[] {1,2}, new int[] {3,2}, new int[] {2,4}, new int[] {5,6}, new int[] {3,5} };
        int[] queries = new int[] { 1, 2, 3, 4, 5, 6 };
        int[] result = solution.MaxBeautyWithCompression(items, queries);
        Console.WriteLine(string.Join(" ", result));
    }
}

This Python code leverages hashing and set operations, together with bisect for indexing, to maintain an optimal list of prices, enabling quick answers to queries through efficient DP-based preparation of price possibilities.

Complexity

Time Complexity: O((n + m) log(n + m)) due to sorting in compression phase.
Space Complexity: O(n + m) manages compressed pricing lists and results mappings.

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.

function maximumBeauty(items: number[][], queries: number[]): number[] {
    const n = items.length;
    const m = queries.length;
    items.sort((a, b) => a[0] - b[0]);
    const idx: number[] = Array(m)
        .fill(0)
        .map((_, i) => i);
    idx.sort((i, j) => queries[i] - queries[j]);
    let [i, mx] = [0, 0];
    const ans: number[] = Array(m).fill(0);
    for (const j of idx) {
        while (i < n && items[i][0] <= queries[j]) {
            mx = Math.max(mx, items[i][1]);
            ++i;
        }
        ans[j] = mx;
    }
    return ans;
}
func maximumBeauty(items [][]int, queries []int) []int {
	sort.Slice(items, func(i, j int) bool {
		return items[i][0] < items[j][0]
	})
	n, m := len(items), len(queries)
	idx := make([]int, m)
	for i := range idx {
		idx[i] = i
	}
	sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] })
	ans := make([]int, m)
	i, mx := 0, 0
	for _, j := range idx {
		for i < n && items[i][0] <= queries[j] {
			mx = max(mx, items[i][1])
			i++
		}
		ans[j] = mx
	}
	return ans
}
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.

function maximumBeauty(items: number[][], queries: number[]): number[] {
    items.sort((a, b) => a[0] - b[0]);
    const n = items.length;
    for (let i = 1; i < n; ++i) {
        items[i][1] = Math.max(items[i][1], items[i - 1][1]);
    }
    const ans: number[] = [];
    for (const q of queries) {
        let l = 0,
            r = n;
        while (l < r) {
            const mid = (l + r) >> 1;
            if (items[mid][0] > q) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        ans.push(--l >= 0 ? items[l][1] : 0);
    }
    return ans;
}
func maximumBeauty(items [][]int, queries []int) []int {
	sort.Slice(items, func(i, j int) bool {
		return items[i][0] < items[j][0]
	})
	n, m := len(items), len(queries)
	prices := make([]int, n)
	prices[0] = items[0][0]
	for i := 1; i < n; i++ {
		prices[i] = items[i][0]
		items[i][1] = max(items[i][1], items[i-1][1])
	}
	ans := make([]int, m)
	for i, q := range queries {
		j := sort.SearchInts(prices, q+1) - 1
		if j >= 0 {
			ans[i] = items[j][1]
		}
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Sort and Binary Search Approach

Time Complexity: O((n + m) log n) due to efficient sorting and searching.
Space Complexity: O(n) for tracking maximum beauties.

Coordinate Compression and Dynamic Programming

Time Complexity: O((n + m) log(n + m)) due to sorting in compression phase.
Space Complexity: O(n + m) manages compressed pricing lists and results mappings.

Sorting + Offline Query–
Sorting + Binary Search–

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

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.

Comments

Now write it yourselfClose this page and solve Most Beautiful Item for Each Query in the editor, without looking.
Practise Most Beautiful Item for Each Query