Most Beautiful Item for Each Query — LeetCode 2070 Python Solution

MediumArrayBinary SearchSorting
Problem
#2070
Reading time
3 min

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.

Example

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.

Python solution

Python
class Solution:
    def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
        items.sort()
        n, m = len(items), len(queries)
        ans = [0] * len(queries)
        i = mx = 0
        for q, j in sorted(zip(queries, range(m))):
            while i < n and items[i][0] <= q:
                mx = max(mx, items[i][1])
                i += 1
            ans[j] = mx
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n + m \times \log m)
SpaceO(\log n + m) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2070. Most Beautiful Item for Each Query is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2070. Most Beautiful Item for Each Query?
LeetCode 2070. Most Beautiful Item for Each Query is rated Medium on LeetCode.
What is the time complexity of LeetCode 2070. Most Beautiful Item for Each Query?
The Python solution on this page runs in O(n \times \log n + m \times \log m).
What is the space complexity of LeetCode 2070. Most Beautiful Item for Each Query?
The Python solution on this page uses O(\log n + m) auxiliary space.
What topics does LeetCode 2070. Most Beautiful Item for Each Query cover?
LeetCode 2070. Most Beautiful Item for Each Query is tagged Array, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview